开发者

Narrow down jQuery results

I've done a search for elements as follows:

var names = $('[name="' + name + '"]');

how do I go about narrowing that result down further, say for example, search for particular values?

The obvious answer is to do:

var names = $('[name="' + name + '"][value="' + value + '"]');

however I specifically wan开发者_如何学运维t to split it into 2 steps. I looked at find() and has(), however both look within the dom rather than the dom attributes.

Any help would be much appreciated.


Use .filter instead:

var names = $('[name="' + name + '"]').filter('[value="' + value + '"]');

If you'd rather avoid (potentially unsafe) string concatenation, you can use a filter function instead:

$(selector)
.filter(function() {
    return (this.attr('name') === name);
})
.filter(function() {
    return (this.attr('value') === value);
});


Just to complement @Alnitak answer, you can have multiple filters in the same first query, example:

$('[name="' + name + '"]')
                         .filter('[value="value1"']).doStuff({})
                         .end() //goes back to '[name="' + name + '"]
                         .filter('[value="value2"']).doStuffTwo({});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜