【问题标题】:$(window) bind hashchange how to check part hash changed?$(window) bind hashchange 如何检查部分散列变化?
【发布时间】:2011-12-03 16:28:00
【问题描述】:

我正在学习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 hashchange 是否从 apple => banana 更改了哈希部分?谢谢。

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

【问题讨论】:

  • 第二次更新的hash不仅改变了水果名称,还改变了数量。

标签: jquery hashchange


【解决方案1】:

将哈希值存储在一个变量中,并在函数结束时更新该变量。考虑:

(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];
    }
})()

【讨论】:

    【解决方案2】:

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

    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;
    });
    

    【讨论】:

    • 我可以检测到(window.location)的变化并处理它吗? (不带 jquery)
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 2022-01-24
    • 1970-01-01
    • 2019-12-20
    • 2015-11-15
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多