jQuery $(window) bind hashchange 如何检查部分哈希改变?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7699073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:11:06  来源:igfitidea点击:

$(window) bind hashchange how to check part hash changed?

jqueryhashchange

提问by Giberno

I am studing Google Ajax Crawlable

我正在学习 Google Ajax Crawlable

I use $(window) bind hashchangeto control ajax page loading.

$(window) bind hashchange用来控制ajax页面加载。

my url like: domain.com/#!/keywords&num=1

我的网址像: domain.com/#!/keywords&num=1

there has two kind of change

有两种变化

  1. domain.com/#!/apple&num=1=> domain.com/#!/apple&num=2

  2. domain.com/#!/apple&num=1=> domain.com/#!/banana&num=1

  1. domain.com/#!/apple&num=1=> domain.com/#!/apple&num=2

  2. domain.com/#!/apple&num=1=> domain.com/#!/banana&num=1

so how to check if $(window) bind hashchangechanged hash part from apple=> banana? Thanks.

那么如何检查是否$(window) bind hashchangeapple=>更改了哈希部分banana?谢谢。

$(window).bind('hashchange', function() {
    // make a judge like  if(){}else{}
});

回答by Rob W

Store the hash in a variable, and update the variable at the end of the function. Consider:

将散列存储在变量中,并在函数结束时更新变量。考虑:

(function(){
    var lastHash = location.hash;
    $(window).bind('hashchange', function() {
        var newHash = location.hash;
        // Do something
        var diff = compareHash(newHash, lastHash);
        alert("Difference between old and new hash:\n"+diff[0]+"\n\n"+dif[1]);

        //At the end of the func:
        lastHash = newHash;
    });

    function compareHash(current, previous){
        for(var i=0, len=Math.min(current.length, previous.length); i<len; i++){
            if(current.charAt(0) != previous.charAt(0)) break;
        }
        current = current.substr(i);
        previous = previous.substr(i);
        for(var i=0, len=Math.min(current.length, previous.length); i<len; i++){
            if(current.substr(-1) != previous.substr(-1)) break;
        }

        //Array: Current = New hash, previous = old hash
        return [current, previous];
    }
})()

回答by maxedison

I would store the original hash in a variable, and then examine the new hash to judge the change. Once that is done, set the new hash to be the original:

我会将原始散列存储在一个变量中,然后检查新散列以判断更改。完成后,将新散列设置为原始散列:

var originalHash = window.location.hash;
$(window).bind('hashchange', function() {
    var newHash = window.location.hash;
    //do your stuff based on the comparison of newHash to originalHash

    originalHash = newHash;
});