0

I need a function to select all elements with a custom attribute, and take its name and value. for example:

<input type="text" my:name="koni" my:age="20" my:city="New York" />

Note that my is always the same, but that behind not. in my function i then want to say:

var attr = //here should be the attribute (attr, or attr2)

and

var value = //here should be the value (test, or hello)

how can i make that?

Edit: sorry, forgot to paste the html.

i want to loop throu each input that has such custom my attributes, and get the value and the key in an array. for this example, i should have:

key = name, value = koni

and

key = age, value = 20

...

4

2 回答 2

1

我认为没有一种简单的方法可以使用 jquery 选择器一举完成此操作,因为您不知道要查找的属性的确切名称。(您只知道它的前缀。)所以,也许您可​​以遍历所有输入,并遍历属性检查任何所需的匹配项?

$('input').each(function() {
    var result = {};                                // to hold any results we might find
    var attrs = this.attributes;                    // this array is provided by the DOM
    for (var idx in attrs) {
        var attrName = attrs[idx].name;
        if (/^my:/.test(attrName)) {                 // must start with this hardcoded pattern
            var key = attrName.substring(3);        // skip first 3 chars
            var value = $(this).attr(attrName);
            result[key] = value;
        }
    }
    // do something with your result obj here...
    if (result['name']) {
        alert('found input with my:name of ' + result['name']);
    }
});

我将结果放在一个对象而不是一个数组中(这似乎更有意义),但这应该给你一个大致的想法,如果你想改进它的话。

祝你好运!

于 2009-12-03T05:59:05.013 回答
0

你应该可以选择

<div cheese="brie">foobar</div>

使用

var items = $("div[cheese]");
于 2009-12-02T16:35:02.547 回答