本文介绍了覆盖函数表达式事件侦听器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试覆盖附加到事件侦听器的函数,但是当触发事件时,仍会调用旧的函数。
I'm trying to override the function attached to the event listener but when the event is triggered the old one is still called.
var element;
var newHandler = () => {
if((element = this.getElementsByClassName('someClass')[0]) != null){
this.removeEventListener('DOMNodeInserted', handler )
element.insertAdjacentHTML('beforeend', "<a>Hello</a>");
}
}
var handler = () => {
handler = newHandler;
var scriptTag = document.createElement('script');
scriptTag.src = "someScript.js";
document.head.appendChild(scriptTag);
}
document.addEventListener('DOMNodeInserted', handler);
任何一种帮助都非常感谢。
多谢!
Any kind of help is really appreciated.Thanks a ton!
推荐答案
找到了解决方案
var element;
var newHandler = () => {
if((element = this.getElementsByClassName('someClass')[0]) != null){
document.removeEventListener('DOMNodeInserted', intermediary )
element.insertAdjacentHTML('beforeend', "<a>Hello</a>");
}
}
var handler = () => {
handler = newHandler;
var scriptTag = document.createElement('script');
scriptTag.src = "someScript.js";
document.head.appendChild(scriptTag);
}
var intermediary = () => handler();
document.addEventListener('DOMNodeInserted', intermediary );
我认为问题是由某种一级缓存引起的。
I think the problem was caused by a kind of first level cache.
这篇关于覆盖函数表达式事件侦听器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!