Jquery - more efficient to use multiple selectors, or each

若如初见. 提交于 2019-12-11 07:28:23

问题


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")));


来源:https://stackoverflow.com/questions/4597234/jquery-more-efficient-to-use-multiple-selectors-or-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!