ChatGPT解决这个技术问题 Extra ChatGPT

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

Is there any difference between the following code?

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

and

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

a
andreister

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

many matching elements would create many identical handlers and thus increase memory footprint 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");

What about: $('button.alert').on('click', function() { alert(1); }); ?
@andreister : correct me if I'm wrong but I believe that another advantage is the usage of namespaces when using on('click' ...), see stackoverflow.com/a/3973060/759452 ie. on('click.darkenallothersections' ...) and at the same time have on('click.displaynextstep' ...) , then I can unbind only the one I choose using .unbind('click.displaynextstep')
g
gilly3

Is there any difference between the following code?

No, there is no functional difference between the two code samples in your question. .click(fn) is a "shortcut method" for .on("click", fn). From the documentation for .on():

There are shorthand methods for some events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

Note that .on() differs from .click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas .click() does not. When .on() is called without a selector parameter, it behaves exactly the same as .click(). If you want event delegation, use .on().


what about the performance issue pointed out my @andreister ?
@rubo77 negligible at best. We're taking single-figure milliseconds.
@RoryMcCrossan that's a big deal for me though - I am looking for this because i have up to 3000 questions on a page that need events. One milisec each makes my page take 3 seconds longer to perform. Your comment isn't helpful for big lists.
The bigger issue is why you have 3000 questions on a page. If you follow good UI patterns you should never have that much information on a page. Look into paging, or lazy loading. Even using event delegation to have a single event handler for all those elements would be better.
@rubo77 - The performance gain is only seen when using event delegation by passing a selector parameter. If you call .on() without a selector parameter there is no performance improvement over using .click().
I
Interrobang

.on() is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both .bind() and .live() into one function that alters behavior as you pass it different parameters.

As you have written your example, there is no difference between the two. Both bind a handler to the click event of #whatever. on() offers additional flexibility in allowing you to delegate events fired by children of #whatever to a single handler function, if you choose.

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });

"Bind to all links inside #whatever, even new ones created later." Isn't that exactly what .live() does? Also, this seems to contradict with the other answers which say that it only has the functionality of .click(), and therefore doesn't apply to future events.
@babonk - This doesn't contradict the other answers, because as Interrobang said in the first paragraph .on() can do what .click() does and do what .bind() and .live() do - it depends what parameters you call it with. (Some other answers mentioned this too.) Note though that "Bind to all links inside #whatever" is not what .live() does, it's what .delegate() does. .live() binds to all inside document rather than letting you specify the container. Note also .live() is deprecated from jQuery 1.7 onwards.
+1 for delegated events: "By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers." api.jquery.com/on
n
nnnnnn

As mentioned by the other answers:

$("#whatever").click(function(){ });
// is just a shortcut for
$("#whatever").on("click", function(){ })

Noting though that .on() supports several other parameter combinations that .click() doesn't, allowing it to handle event delegation (superceding .delegate() and .live()).

(And obviously there are other similar shortcut methods for "keyup", "focus", etc.)

The reason I'm posting an extra answer is to mention what happens if you call .click() with no parameters:

$("#whatever").click();
// is a shortcut for
$("#whatever").trigger("click");

Noting that if you use .trigger() directly you can also pass extra parameters or a jQuery event object, which you can't do with .click().

I also wanted to mention that if you look at the jQuery source code (in jquery-1.7.1.js) you'll see that internally the .click() (or .keyup(), etc.) function will actually call .on() or .trigger(). Obviously this means you can be assured that they really do have the same result, but it also means that using .click() has a tiny bit more overhead - not anything to worry or even think about in most circumstances, but theoretically it might matter in extraordinary circumstances.

EDIT: Finally, note that .on() allows you to bind several events to the same function in one line, e.g.:

$("#whatever").on("click keypress focus", function(){});

T
Tushar

.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).


M
Mustkeem K

Here you will get list of diffrent ways of applying the click event. You can select accordingly as suaitable or if your click is not working just try an alternative out of these.

$('.clickHere').click(function(){ 
     // this is flat click. this event will be attatched 
     //to element if element is available in 
     //dom at the time when JS loaded. 

  // do your stuff
});

$('.clickHere').on('click', function(){ 
    // same as first one

    // do your stuff
})

$(document).on('click', '.clickHere', function(){
          // this is diffrent type 
          //  of click. The click will be registered on document when JS 
          //  loaded and will delegate to the '.clickHere ' element. This is 
          //  called event delegation 
   // do your stuff
});

$('body').on('click', '.clickHere', function(){
   // This is same as 3rd 
   // point. Here we used body instead of document/

   // do your stuff
});

$('.clickHere').off().on('click', function(){ // 
    // deregister event listener if any and register the event again. This 
    // prevents the duplicate event resistration on same element. 
    // do your stuff
})

$('.clickHere').off().on() was just what I needed. Thanks!
S
SLaks

No, there isn't.
The point of on() is its other overloads, and the ability to handle events that don't have shortcut methods.


d
dana

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().


t
tw0shoes

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


A
Alper Bilgil

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.


A
Astra Bear

NEW ELEMENTS

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

elements selected by the first selector eg $("body") must exist at the time the declaration is made otherwise there is nothing to attach to. you must use the three arguments in the .on() function including the valid selector for your target elements as the second argument.


R
Richard de Wit
$('.UPDATE').click(function(){ }); **V/S**    
$(document).on('click','.UPDATE',function(){ });

$(document).on('click','.UPDATE',function(){ });

it is more effective then $('.UPDATE').click(function(){ }); it can use less memory and work for dynamically added elements. some time dynamic fetched data with edit and delete button not generate JQuery event at time of EDIT OR DELETE DATA of row data in form, that time $(document).on('click','.UPDATE',function(){ }); is effectively work like same fetched data by using jquery. button not working at time of update or delete:

https://i.stack.imgur.com/IgTcH.png


$(document).on('click','.UPDATE',function(){ }); 1)it is more effective then $('.UPDATE').click(function(){ }); 2)it can use less memory and work for dynamically added elements. 3) some time dynamic fetched data with edit and delete button not generate JQuery event at time of EDIT OR DELETE DATA of row data in form, that time $(document).on('click','.UPDATE',function(){ }); is effectively work.[like same fetched data by using jquery. button not working at time of update or delete