Jquery - more efficient to use multiple selectors,

2019-07-27 15:26发布

问题:

I have something like this

<input class = "Class1"/>
<input class = "Class2"/>
<input class = "Class3"/>
<input class = "Class4"/>
...
..
.

$(".Class1").someFunction("data1");
$(".Class2").someFunction("data2");
$(".Class3").someFunction("data3");
$(".Class4").someFunction("data4");
...
..
.

is it more efficient to do that or something like this:

<input something="data1"/>
<input something="data2"/>
<input something="data3"/>
<input something="data4"/>
...
..
.
$("[something]").each($(this).someFunction($(this).attr("something")));

ideas?

回答1:

As far as fastest selectors go it would be better to do:

<div id="container">
    <input data-something="1" />
    <input data-something="2" />
    <input data-something="3" />
    <input data-something="4" />
</div>

Then you can do:

$('#container input').each(function(){});


回答2:

Irrespective of how you select them, you'll need to do an each() anyway if your code example is anything like you're real code.This is because you're passing unique data to each function call.

But you should add a tagName to the selector at the very least.

$("input[something]").each(function() {
    $(this).someFunction($(this).attr("something"));
});

Without the tagName, jQuery will need to look at every element on the page, instead of just input elements.



回答3:

^= operator matches starts with too:

$("input[class^=Class]").each($(this).someFunction($(this).attr("something")));