简体   繁体   English

取消绑定元素的事件,这些元素以后将添加到DOM中

[英]Unbind events on elements that will be added to DOM later

I have a div with class="backdrop". 我有一个class =“ backdrop”的div。 This will be added to DOM when I click a button. 当我单击一个按钮时,它将被添加到DOM中。 To this is bound an event of 'wheel'. 与此相关的是“车轮”事件。

I cannot avoid the binding of the event(happening through library) So i will want to unbind this globally. 我无法避免事件的绑定(通过库发生),所以我将要全局取消绑定。

I tried : $(".modal-backdrop.am-fade").unbind('wheel'); 我试过了: $(".modal-backdrop.am-fade").unbind('wheel');

This works but I have to write this statement after each time the div is added to the DOM. 这可行,但是每次将div添加到DOM之后,我都必须编写此语句。 I want something which I can write only once and would apply to all the divs which would be added to the DOM in future

I want something which I can write only once and would apply to all the divs which would be added to the DOM in future 我想要只写一次的东西,并将其应用于将来将添加到DOM的所有div中

If code in the library you're using is adding elements and binding events to them, you'll have to unbind them as you go, there's no alternative. 如果您正在使用的库中的代码正在添加元素并将事件绑定到它们,那么您就必须在进行操作时取消绑定它们,没有其他选择。

If you already have some way of triggering that (the library tells you when it adds a div), then you'll just have to have that code respond to that event. 如果您已经有某种触发方式(该库会告诉您何时添加div),那么您只需要使该代码响应该事件即可。

If you don't already have some way of triggering it, you can use mutation observers to watch for the divs being added so you can unbind them. 如果您还没有触发它的方法,则可以使用突变观察器来监视正在添加的div,以便可以取消绑定它们。 They're well-supported by modern browsers. 它们得到了现代浏览器的良好支持。 Slightly less modern browsers may have sufficient support for the old mutation events that you can use a library that provides a mutation observer polyfill using mutation events (just search for "mutation observer polyfill"). 较不那么现代的浏览器可能对旧的突变事件有足够的支持,您可以使用一个库,该库提供使用突变事件的突变观察者polyfill(只需搜索“ mutationobserver polyfill”)。 Worst case, on really old browsers, you'll have to poll. 最坏的情况是,在真正的旧浏览器上,您必须进行轮询。


Of course, the best answer is to either stop using the library if it doesn't do what you want, or modify it (this is JavaScript, after all) so it doesn't do what you don't want. 当然,最好的答案是要么停止使用该库(如果它不执行您想要的操作),要么对其进行修改(毕竟是JavaScript),以便它不执行您不想要的操作。

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

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