gpt4 book ai didi

javascript - window.addEventListener 不工作但 window.onhashchange 工作?

转载 作者:行者123 更新时间:2023-11-29 10:07:29 27 4
gpt4 key购买 nike

window.addEventListener("hashchange",myFunction);
console.log(window.onhashchange); //This one prints NULL

window.onhashchange = myFunction;
console.log(window.onhashchange); // This one working fine.

function myFunction() {
alert("The anchor part has changed!");
}

为什么我无法使用 addEventListener 方法附加事件监听器?但是 window.onhashchange 工作正常

编辑我确实使用了“hashchange”而不是“onhashchange”,这是一个错字。

最佳答案

没有onhashchange 事件。 一个hashchange事件:

window.addEventListener('hashchange', myFunction, false);

同样,没有onclick 事件,但是 click 事件:

element.addEventListener('click', someFunction, false);

测试绑定(bind)事件的 on* 属性不是验证回调是否已绑定(bind)的合适方法。对于测试,您必须以某种方式触发事件并在回调中进行测试:

window.onhashchange = function () {
console.log('onhashchange property works');
};

window.addEventListener('hashchange', function () {
console.log('addEventListener method works');
}, false);
<a href="#example">Click this to test</a>

成功绑定(bind)的回调不会通过该属性公开。

关于javascript - window.addEventListener 不工作但 window.onhashchange 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40518712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com