简体   繁体   中英

.off(), .undelegate(), .unbind() event only from copied element

I'm using

$(document).on('click', '.mySelector', function () {
    //do something
});

To delegate events to buttons. Next I'm using .clone(true) to copy div which containing few buttons with delegated in to it events. My question is how do I remove events form selected new created buttons? I'm tried:

$(document).unbind('click', $(myNewDiv).find('.mySelector'));

Somehow it's removing events from all $('.mySelector') in whole document not only from this inside 'myNewDiv' object.

I have seen documentation of jQuery .off() and .undelegate() and they accept only string like selector (my div can't have any unique ID).

Is any option to remove events from selected elements inside jQuery object when they are delegated to document?

You can add a class to your clones:

var $clone = $original.clone(true).addClass("clone");

And reject that class in your delegated handler:

$(document).on("click", ".mySelector:not(.clone)", function() {
    // Do something...
});
$(document).on('click',  '.mySelector', function(){
   //do something
});

the code above means, "attach a click handler to the document, so whenever any element that corresponds to the '.mySelector' selector is clicked, fire the handler".

whenever you clone an element, you clone its class as well, therefore it will suit the '.mySelector' too.

the handler that you have delegated is attached to the document and not to the elmenets themselves. in order for the new elements to not fire the handler, you must make them not fit the selector. so either change their class to '.mySelector2' after cloning, or whatever.

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