【发布时间】:2018-05-04 14:07:36
【问题描述】:
与 Chrome 和 Firefox 相比,Edge 执行一段 Javascript 的方式最近遇到了奇怪的不一致。
当附加一个点击处理程序时(错误的,偶然的),Edge 的反应如预期的那样。但是 Chrome 和 Firefox 忽略了错误的点击处理程序,隐藏了我的错误。
button.addEventListener("click", functionOne);
function functionOne(e) {
console.log('functionOne called');
functionTwo(e);
}
function functionTwo(e) {
console.log('functionTwo called');
// My intial mistake was here: According to my application logic,
// I should have removed the event listener for functionOne. Whoops.
button.removeEventListener("click", functionThree);
console.log("Doing some asynchronous work...");
// Same here: I should have re-added the event listener for functionOne
button.addEventListener("click", functionThree);
}
// This function is never called by FF and Chrome, but it is called in Edge
function functionThree(e) {
console.error('functionThree called');
}
我打算在做一些异步工作时删除functionOne 的事件侦听器,然后在异步调用完成后重新连接。我的错误是调用 removeEventListener() 时引用了错误的函数 (functionThree),然后将另一个事件侦听器附加到 button,它也调用了 functionThree。
但奇怪的是,代码在 Chrome 和 Firefox 中按预期工作。只有在 Edge 中尝试时,我才注意到 Edge 调用了functionThree,而 Chrome 和 Firefox 都忽略了它。
有人可以解释这种行为吗? 为什么 Chrome 和 Firefox 不调用 functionThree 虽然我附加了一个事件监听器?为什么 Edge 调用它?
浏览器版本:
FireFox 59.0.2
Edge 41.16299.371.0
Chrome 66.0.3359.139
TL;DR - Firefox/Chrome 没有像我预期的那样附加事件监听器。 Edge 做到了。
【问题讨论】:
标签: javascript google-chrome dom-events microsoft-edge addeventlistener