将哈希值存储在变量中,并在函数末尾更新变量。考虑:
(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];
}
})()