jquery selector performance

2019-07-02 00:35发布

问题:

Is there a more performant way to write this.

$('#test').find('option:selected[value!=""]')

回答1:

You can tweak it at little, but using methods instead of Sizzle:

$('#test').find('option').filter(function() {
    return this.selected && this.value.length
});

Benchmark: http://jsperf.com/sizzle-vs-methods-filter/12

.filter() is about 70% faster for me.



回答2:

Well, there will always only be one selected, so you don't need a find() handler in my opinion.

I'll just write it like this:

$('#test option:selected[value!=""]')

I haven't tested it yet.