开发者

onHashChange: native Javascript function works well, but!

开发者 https://www.devze.com 2023-03-08 00:38 出处:网络
I found this peace of code some where on the web. I tried it and it works fine: var onHashChange = function(event) {

I found this peace of code some where on the web. I tried it and it works fine:

var onHashChange = function(event) {

    //get hash function
    var getHashValue = function() {

        var arr = window.location.hash.split("#");

        var hasValue = arr[1];

        //sets default
        if (typeof hasValue == "undefined") {
            return false;
        }

        var hashLen = hasValue.indexOf("?");
        if(hashLen>0){
            hasValue = hasValue.substring(0,hashLen);
        }
        return hasValue;

    }

    //last hash
    var lastHash = getHashValue();

    //checker
    (function watchHash() {
        var hash = getHashValue();

        if (hash !== lastHash) {
            event();
            lastHash = hash;
        }

        var t = setTimeout(watchHash, 100);

    })();

} 

BUT when the function that would be called in the onHashChange many time, it will be repeated for ever.

onHashChange(function() {
  console.log("changed"); 
});

when am at the same page and the hash is being changed, the console.lo开发者_运维知识库g will be full of "changed" text even when I made only 3 changes for the hash in the page!

Well, am calling a function "instead of console.log" that at the same time will callback onHashChange again

Any trick to get over it?

Thanks :)


This should work well on hash change and url change via history.replaceState and history.pushState!

  var onUrlChange = function(event) {
    var getHashValue = function () {
      var arr = window.location.hash.split("#");
      var hasValue = arr[1];
      if (typeof hasValue == "undefined") {
        return false;
      }
      var hashLen = hasValue.indexOf("?");
      if (hashLen > 0) {
        hasValue = hasValue.substring(0, hashLen);
      }
      return hasValue;
    }

    var getUrlValue = function () {return window.location.pathname;}

    var lastHash = getHashValue();
    var lastUrl = getUrlValue();

    (function watchPath() {
      var hash = getHashValue();
      var url = getUrlValue();
      if (hash !== lastHash) {
        event();
        lastHash = hash;
      }
      if (url !== lastUrl) {
        event();
        lastUrl = url;
      }

      var t = setTimeout(watchPath, 100);

    })();
  }

  onUrlChange(function () {
    //somthing
  });
0

精彩评论

暂无评论...
验证码 换一张
取 消