Difference between .on('click') vs .click()

后端 未结 12 2503
礼貌的吻别
礼貌的吻别 2020-11-21 05:22

Is there any difference between the following code?

$(\'#whatever\').on(\'click\', function() {
     /* your code here */
});

and

相关标签:
12条回答
  • 2020-11-21 05:44

    I think, the difference is in usage patterns.

    I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

    Consider the following html:

    <html>
        <button id="add">Add new</button>
        <div id="container">
            <button class="alert">alert!</button>
        </div>
    </html>
    

    where we add new buttons via

    $("button#add").click(function() {
        var html = "<button class='alert'>Alert!</button>";
        $("button.alert:last").parent().append(html);
    });
    

    and want "Alert!" to show an alert. We can use either "click" or "on" for that.


    When we use click

    $("button.alert").click(function() {
        alert(1);
    });
    

    with the above, a separate handler gets created for every single element that matches the selector. That means

    1. many matching elements would create many identical handlers and thus increase memory footprint
    2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

    When we use .on

    $("div#container").on('click', 'button.alert', function() {
        alert(1);
    });
    

    with the above, a single handler for all elements that match your selector, including the ones created dynamically.


    ...another reason to use .on

    As Adrien commented below, another reason to use .on is namespaced events.

    If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

    $("#element").on("click.someNamespace", function() { console.log("anonymous!"); });
    

    with unbinding via

    $("#element").off("click.someNamespace");
    
    0 讨论(0)
  • 2020-11-21 05:44

    As far as ilearned from internet and some friends .on() is used when you dynamically add elements. But when i used it in a simple login page where click event should send AJAX to node.js and at return append new elements it started to call multi-AJAX calls. When i changed it to click() everything went right. Actually i did not faced with this problem before.

    0 讨论(0)
  • 2020-11-21 05:49

    They appear to be the same... Documentation from the click() function:

    This method is a shortcut for .bind('click', handler)

    Documentation from the on() function:

    As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off().

    0 讨论(0)
  • 2020-11-21 05:50

    They've now deprecated click(), so best to go with on('click')

    0 讨论(0)
  • 2020-11-21 05:52

    .click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready.

    .on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).

    0 讨论(0)
  • 2020-11-21 05:53

    NEW ELEMENTS

    As an addendum to the comprehensive answers above to highlight critical points if you want the click to attach to new elements:

    1. elements selected by the first selector eg $("body") must exist at the time the declaration is made otherwise there is nothing to attach to.
    2. you must use the three arguments in the .on() function including the valid selector for your target elements as the second argument.
    0 讨论(0)
提交回复
热议问题