How to execute a js function based on url hash url#nameoffunction

后端 未结 5 1235
执念已碎
执念已碎 2021-01-02 09:08

I saw some of websites executes a JavaScript function based on has in the URL. For example,

when I access http://domain.com/jobs#test

then the website execut

5条回答
  •  伪装坚强ぢ
    2021-01-02 09:56

    If you don't need to support old browsers like IE6 and IE7 you can use:

    window.onhashchange = function(){
      switch(location.hash) {
        case '#hash1':
          //do something
        break;
        case '#has2':
          //do something else
        break;
      }
    }
    

    But if you have to support older browsers you need to poll:

    var oldHash = location.hash;
    setInterval(function(){
      if(location.hash !== oldHash){
        oldHash = location.hash;
        //hash changed do something
      }
    }, 120);
    

提交回复
热议问题