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

僤鯓⒐⒋嵵緔 提交于 2019-11-30 05:40:59

问题


I am studing Google Ajax Crawlable

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

my url like: 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

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

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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7699073/window-bind-hashchange-how-to-check-part-hash-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!