开发者

jquery custom selector with colon

开发者 https://www.devze.com 2022-12-13 13:39 出处:网络
I need a function to select all elements with a custom attribute, and take its name and value. for example:

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 t开发者_运维百科hrou 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

...


I don't think there is an easy way to do this in one easy swoop using a jquery selector, since you don't know the exact name of the attribute you're looking for. (You only know its prefix.) So, perhaps you could just loop through all inputs, and walk through the attributes checking for any desired matches?

$('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']);
    }
});

I'm putting the results in an object instead of an array (which seems to make more sense) but this should give you the general idea should you care to refine this at all.

Best of luck!


You should be able to select

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

using

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号