jquery use of bind vs on click

前端 未结 3 965
無奈伤痛
無奈伤痛 2020-12-02 12:54

I have come across several methods for handling click events in jquery:

bind:

$(\'#mydiv\').bind(\'click\', function() {
    ...
});
<
3条回答
  •  無奈伤痛
    2020-12-02 13:45

    To your first question: there's also .delegate, which was superseded by .on as of jQuery 1.7, but still is a valid form of binding event handlers.

    To your second question: You should always use .on like the docs say, but you should also pay attention on how to use .on, because you can either bind the event handler on an object itself or a higher level element and delegate it like with .delegate.

    Say you have an ul > li list and want to bind a mouseover event to the lis. Now there are two ways:

    • $('ul li').on('mouseover', function() {});
    • $('ul').on('mouseover', 'li', function() {});

    The second one is preferable, because with this one the event handler gets bound to the ul element once and jQuery will get the actual target item via event.currentTarget (jQuery API), while in the first example you bind it to every single list element. This solution would also work for list items that are being added to the DOM during runtime.

    This doesn't just work for parent > child elements. If you have a click handler for every anchor on the page you should rather use $(document.body).on('click', 'a', function() {}); instead of just $('a').on('click', function() {}); to save a lot of time attaching event handlers to every element.

提交回复
热议问题