Jquery - 更有效地使用多个选择器,或每个选择器 [英] Jquery - more efficient to use multiple selectors, or each

查看:97
本文介绍了Jquery - 更有效地使用多个选择器,或每个选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西

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


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

是否更有效率地执行此操作或类似操作:

 < input something =data1/> 
< input something =data2/>
< input something =data3/>
< input something =data4/>
...
..

$([something])。each($(this).someFunction($(this).attr(something)));

点子

解决方案<无论您如何选择它们,无论如何,如果您的代码示例与您是真实代码一样,则无论如何您都需要执行 each()。这是因为你正在向每个函数调用传递唯一的数据。



但至少应该在选择器中添加一个 tagName

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

如果没有 tagName ,jQuery将需要查看页面上的每个元素,而不是 input 元素。


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?

解决方案

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.

这篇关于Jquery - 更有效地使用多个选择器,或每个选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆