[英]Any performance gain when binding to event on multiple elements at once?
I was wondering if attaching an event handler to a jQuery collection is faster than looping over the elements and attaching the event handler on each element.我想知道将事件处理程序附加到 jQuery 集合是否比循环元素并在每个元素上附加事件处理程序更快。
var stuff = $();
// then some code that builds the list
// stuff = stuff.add(...);
stuff.on('change', ...
versus an array that holds the elements:与包含元素的数组相比:
for (var i = 0; i < stuff.length; i++)
$(stuff[i]).on('change', ...
I'm asking becaue I'm in the position of having to choose the event ( change
or input
) based on the type of input我问是因为我处于必须根据输入类型选择事件(
change
或input
)的位置
I would suggest doing stuff.on
over $(stuff[i]).on
because jQuery essentially does that for you under the hood.我建议在
$(stuff[i]).on
做stuff.on
$(stuff[i]).on
因为 jQuery 本质上是在stuff.on
为你做的。
If you look at the source code you'll see that they do the following:如果您 查看源代码,您会看到它们执行以下操作:
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
where add
is the actual function used to attach event listeners.其中
add
是用于附加事件侦听器的实际函数。 If you're absolutely concerned with performance than you can push it faster by bypassing jQuery all together and attach listeners more manually:如果您绝对关心性能,那么您可以通过绕过 jQuery 并更多地手动附加侦听器来提高性能:
function onChangeListener() { ... }
for (var i = 0, len = stuff.length; i < len; i++) {
stuff[i].addEventListener('change', onChangeListener);
}
But addEventListener
isn't 100% supported by older browsers and jQuery will take care of that detail for you.但是
addEventListener
不是 100% 受旧浏览器支持,jQuery 会为您处理这些细节。
Another major detail to keep in mind is that every time you do $(something)
a new object is created which will definitely make the second method less performant.要记住的另一个主要细节是,每次执行
$(something)
都会创建一个新对象,这肯定会降低第二种方法的性能。
If at all possible, you may want to attach to the parent element (assuming everything in stuff
is under a common parent) and pick up the events there.如果可能,您可能希望附加到父元素(假设东西中的所有
stuff
都在一个共同的父元素下)并在那里获取事件。 That will definitely be the best option if applicable.如果适用,那绝对是最好的选择。
TL;DR Just do $(selector).on(event, callback)
. TL;DR只需执行
$(selector).on(event, callback)
。 You'll save yourself some cycles, memory, and heartache.你会为自己节省一些周期、记忆和心痛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.