简体   繁体   中英

jQuery and chaining

Sometimes I need to use .off() before .on().

My Question is can I chain them both together or should they remain separate?

Can this:

   $('button').off('click');
    $('button;).on('click, function() {
    // code here.
    });

Become this and work the same:

$('button').off('click').on('click', function() {
 // code here
});

Will the .off() execute before the .on() in the chain.

I'm fairly new to chaining this is why I ask.

Yes, it will execute before the .on() method. Basically chaining allows you to write less amount of code and, btw, it fasters it a bit, cause you don't have to find your element multiple times in the DOM tree.(Each time you call $('#yourElmId') you basically call document.getElementById so if you call it twice - you will perform search of it two times and for big projects it's not great at all)

More details on jquery chaining here

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