最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.addEventListener not working but window.onhashchange working? - Stack Overflow

programmeradmin0浏览0评论
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!");
}

Why I am not able to attach event listener using the addEventListener method ? But window.onhashchange working fine

EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.

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!");
}

Why I am not able to attach event listener using the addEventListener method ? But window.onhashchange working fine

EDIT I am indeed using the 'hashchange' not 'onhashchange' it was a typo.

Share Improve this question edited Nov 10, 2016 at 1:39 javanoob asked Nov 10, 2016 at 1:33 javanoobjavanoob 6,42218 gold badges71 silver badges92 bronze badges 1
  • The getter window.onhashchange is not set doesn't mean it is not working. – Derek 朕會功夫 Commented Nov 10, 2016 at 1:44
Add a ment  | 

2 Answers 2

Reset to default 6

There is no onhashchange event. There is a hashchange event:

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

Likewise, there is no onclick event, but there is a click event:

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

testing on* properties for bound events is not an appropriate way to verify that a callback is bound. For testing, you'll have to trigger the event in some manner and have a test within the callback:

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>

Successfully bound callbacks will not be exposed via the property.

I had the same issue and hashchange but function does not fired...

OLD CODE

const router = ()=>{//load new data}
window.addEventListener('hashchange',router())

**This is load new data but page not reload and just how old data, it fixed when i change to **

window.addEventListener('hashchange', () => {
router()})

hope it will help thanks

发布评论

评论列表(0)

  1. 暂无评论