jquery - $(window) 绑定(bind) hashchange 如何检查部分哈希更改?

标签 jquery hashchange

我正在学习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{}
});

最佳答案

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

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

关于jquery - $(window) 绑定(bind) hashchange 如何检查部分哈希更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7699073/

相关文章:

jQuery 事件委托(delegate) + 子目标帮助

javascript - jquery - (...).autocomplete 不是一个函数

javascript - Hashchange 事件监听器在事件处理程序附加到事件之前监听

jquery - anchor 标记破坏具有哈希更改 URL 的页面

ajax - 使用 Ajax 历史记录和书签时,使用 "#!"而不是 "#"总是好的吗?

javascript - Jquery + 最新的哈希更改监听器?

javascript - Php Mysql Ajax 插入多行

javascript - jQuery 用户界面 : Save height and position of divs in cookie

javascript - 使用 div 滚动到某个点

javascript - 哈希变化事件