-1

我试图覆盖附加到事件侦听器的函数,但是当事件被触发时,旧的仍然被调用。

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);

任何形式的帮助都非常感谢。万分感谢!

4

1 回答 1

0

找到了解决方案

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 );

我认为问题是由一种一级缓存引起的。

于 2017-08-16T08:25:54.773 回答