带冒号的jquery自定义选择器

时间:2009-12-02 16:24:27

标签: jquery selector colon

我需要一个函数来选择具有自定义属性的所有元素,并获取其名称和值。例如:

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

请注意,我总是一样,但不是。在我的功能中,我想说:

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

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

我该怎么做?

编辑:抱歉,忘了粘贴html。

我想循环每个具有此类自定义属性的输入,并获取数组中的值和键。对于这个例子,我应该:

key = name, value = koni

key =年龄, 值= 20

...

2 个答案:

答案 0 :(得分: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']);
    }
});

我将结果放在一个对象而不是一个数组(这似乎更有意义)但是如果你想完全改进这个,那么这应该给你一般的想法。

祝你好运!

答案 1 :(得分:0)

您应该可以选择

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

var items = $("div[cheese]");