Change hash without triggering a hashchange event

后端 未结 2 429
借酒劲吻你
借酒劲吻你 2021-02-04 23:30

I\'m using the hash to load content dynamically. To make the back button work I am capturing hash changes. However sometimes I need to change the hash without triggering the has

相关标签:
2条回答
  • 2021-02-05 00:12

    You can have a function like this:

    function updateHash(newHash){
      ...
      oldHash = newHash
    }
    

    then in your setTimeOut you need to do

    function(){
      if(oldHash != currenHash){
        updateHash(currenHash);
      }
    }
    

    So now you can call update hash manually and it won't be triggered by the event. You can also have more parameters in updateHash to do other things.

    By the way, have you looked at the jquery history plugin? http://tkyk.github.com/jquery-history-plugin/

    0 讨论(0)
  • 2021-02-05 00:28

    You could use history.replaceState and append the hash, to replace the current URI without triggering the hashchange event:

    var newHash = 'test';
    
    history.replaceState(null, null, document.location.pathname + '#' + newHash);
    

    JSFiddle example

    0 讨论(0)
提交回复
热议问题