6

我正在学习Google Ajax Crawlable

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

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

有两种变化

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

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

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

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

2 回答 2

14

将哈希值存储在变量中,并在函数末尾更新变量。考虑:

(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];
    }
})()
于 2011-10-08T19:04:12.183 回答
3

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

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;
});
于 2011-10-08T19:04:28.480 回答