简体   繁体   中英

Remove specific jQuery click event from element

I understand event can be removed from an element by using .unbind() or .off(). However I am wondering if is that possible to remove specific click event and leave others attached. For example assuming I have a element with two events attached as follow:

$("#MyDiv").click(function() {
alert("I am first Event");
});

$("#MyDiv").click(function () {
    alert("I am second Event");
});

Is that possible to remove First event and leave second one attached, using some sort of key?

You can use event name spacing and .off()

$("#MyDiv").on('click.first', function () {
    alert("I am first Event");
});

$("#MyDiv").on('click.second', function () {
    alert("I am second Event");
});

$("#MyDiv").off('click.first');

Demo: Fiddle

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