简体   繁体   English

如何在不克隆或访问事件侦听器创建的情况下从元素中删除事件侦听器?

[英]How can I remove an event listener from an element without cloning or access to the event listener creation?

I'm helping someone build a website through a website builder, Kajabi.我正在通过网站建设者 Kajabi 帮助某人建立网站。 Some of the JavaScript code is included by default in the website and there is no way to edit it.一些 JavaScript 代码默认包含在网站中,无法对其进行编辑。 I'm trying to remove an event listener on the window element, but the event listener creation happened in the code that I can't edit.我正在尝试删除窗口元素上的事件侦听器,但事件侦听器的创建发生在我无法编辑的代码中。 This code fires before anything else, so there's no way for me to interrupt it either.这段代码在其他任何事情之前都会触发,所以我也无法中断它。 On dev tools, I tracked down the event handler and found this:在开发工具上,我追踪了事件处理程序并发现了这一点:

(o=g.handle)||(o=g.handle=function(t){return"undefined"!=typeof Ft&&Ft.event.triggered!==t.type?Ft.event.dispatch.apply(e,arguments):void 0})

That's all the information I can find on the event listener.这就是我可以在事件监听器上找到的所有信息。 I understand cloning works to remove event listeners, but removing all listeners from children of the window element would cause trouble.我了解克隆可以删除事件侦听器,但是从窗口元素的子元素中删除所有侦听器会造成麻烦。

Any tips?有小费吗?

Going on with assumptions here from the little code you posted.从您发布的小代码中继续进行假设。 o is g.handle and that's an inline event listener, so you can simply overwrite it if you have access to them. og.handle并且这是一个内联事件侦听器,因此如果您可以访问它们,您可以简单地覆盖它。

g.handle = false;

It seems that code is dispatching a new event from their Ft variable here Ft.event.dispatch.apply(e,arguments) .似乎代码正在从Ft变量的Ft.event.dispatch.apply(e,arguments)分派一个新事件。 It's a bit different than vanilla javascript's .dispatchEvent() but I'm assuming its just an implementation of it.它与 vanilla javascript 的.dispatchEvent()有点不同,但我假设它只是它的一个实现。

If that's not the case and there IS someplace else that's adding an event listener with .addEventListener() that you can't remove because you have no reference to the function, you can do a shallow clone and append the children to the clone element.如果情况并非如此,并且还有其他地方正在使用.addEventListener()添加一个事件侦听器,但由于您没有对该函数的引用,您无法删除该事件侦听器,您可以进行浅克隆并将子代附加到克隆元素。 The cloned element will lose any events attached with addEventListener() but their children will be unaffected.克隆的元素将丢失任何附加到addEventListener()的事件,但它们的子元素不受影响。 You're just appending the original children to the new cloned element.您只是将原始子项附加到新的克隆元素。

let oldElement = document.getElementById("toClone");

// - Shallow clone
let clone = oldElement.cloneNode(false);

// - Adding the original children to the clone
while (oldElement.firstChild) {
    clone.appendChild(oldElement.firstChild);
}

// - Replacing them
oldElement.parentNode.appendChild(clone);
oldElement.remove();

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

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