2011-10-08 71 views
6

我在學習Google Ajax Crawlable

我使用$(window) bind hashchange來控制ajax頁面加載。

我的網址,如:

存在有兩種變化

  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{} 
}); 
+0

第二次更新的散列不僅改變水果名稱,而且還改變水果名稱。 –

回答

13

將散列存儲在變量中,並在函數結束時更新變量。考慮:

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

多麼偉大的工作。謝謝。 – Giberno

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

我可以檢測(window.location)的更改並處理它嗎? (沒有jQuery) – BergP

相關問題