简体   繁体   English

.off(),. undelegate(),. unbind()事件仅来自复制的元素

[英].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. 接下来我使用.clone(true)来复制包含几个按钮的div ,并将其委托给它。 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. 不知何故,它正在从整个文档中的所有$('.mySelector')中删除事件,而不仅仅是来自这个'myNewDiv'对象内部。

I have seen documentation of jQuery .off() and .undelegate() and they accept only string like selector (my div can't have any unique ID). 我见过jQuery .undelegate() .off().undelegate()文档,它们只接受字符串之类的选择器(我的div不能有任何唯一的ID)。

Is any option to remove events from selected elements inside jQuery object when they are delegated to document? 是否可以选择在委托给文档时从jQuery对象中的选定元素中删除事件?

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". 上面的代码意味着“将单击处理程序附加到文档,因此只要单击与'.mySelector'选择器对应的任何元素,就触发处理程序”。

whenever you clone an element, you clone its class as well, therefore it will suit the '.mySelector' too. 每当你克隆一个元素时,你也克隆它的类,因此它也适合'.mySelector'。

the handler that you have delegated is attached to the document and not to the elmenets themselves. 您委派的处理程序附加到文档而不是elmenets本身。 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. 所以要么在克隆之后将它们的类更改为“.mySelector2”,要么等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM