简体   繁体   中英

Binding event handlers to elements using JQuery's .each and .on

I need to bind a handler to the click event on multiple elements on the page and send the value of that element to some other function, but some questions came to mind.

I can achieve the same effect by using .each and binding the handler to each distinct element, or just by using the .on() function to bind them all at once. The latter approach requires fewer explicit method calls, but is it practically faster, or is the work simply being shifted under the hood to jQuery?

Here's the stripped down version of what I meant by above:

<div class="el">a</div>
<div class="el">b</div>
<div class="el">c</div>
<div class="el">d</div>

<script>
// Scenario 1
$('.el').on('click', function() {
    doSomething();
});
// Scenario 2
$('.el').each(function() {
    $(this).on('click', function() {
        doSomething();
    });
});
</script>

Is jQuery doing the same thing under the hood? or are they doing something completely different?

$().on() itself calls each , so it's pretty much the same thing as far as result goes, with the difference that in your scenario 2, where you call each() then on() , on() will still call each() for every object on which you call on() . So it's 5 calls to each vs 1. so it looks like calling each() and then on() is superfluous and so it should be more efficient to call on() directly, but probably in a very very marginal way. Except if you have lots of elements, I don't think you'll see that much of a difference.

You can see in jQuery source code, this is what on() returns:

return this.each( function() {
            jQuery.event.add( this, types, fn, data, selector );
        });

But in such a case, the more efficient way remains using delegated events. Like this:

$(document).on('click', '.el', function(){console.log('delegated')});

You can see in this fiddle, I've added logs to on and each functions to see exactly what happens. This is using jQuery 2.0.2:

http://jsfiddle.net/d2vev3y0/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM