If you call click
once, jQuery will cycle through the entire collection and bind events individually. However, it will do this more efficiently than your alternative, because it does not create a new jQuery object for each element in the set, which will be very slow.
Here is the code from the jQuery source (this is the on
method):
return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); });
(event.js, line 936-8)
jQuery.event.add
, which is a heavy lifting method, does not need a jQuery object; a simple DOM object is what it needs. This loop (which actually does the same as yours) is far superior in performance because a large bottleneck in your $(this)
code is called every time.
Note that the most efficient method would be to use event delegation with the same on
method. It might look like this:
$(document.body).on('click', '.className', funcName);
This means that "for each click inside document.body
check to see if it occurred on the element matching the .className
selector, and if it is executing funcName
." You can replace document.body
with any other element containing all potential .className
elements.
source share