2013-11-26 173 views
0

我在javascript中使用location.hash,以允許用戶在ajax屏幕(在同一個html頁面內動態添加和刪除的div)之間切換。Location.hash導致無限循環

問題是,當我通過javascript更新location.hash時,窗口偵聽器立即觸發!我只需要在後退按鈕實際點擊時觸發此事件,而不是在通過javascript更改歷史記錄時觸發。

我的窗口偵聽代碼:

window.onhashchange = function() { 
    var s; 
    if (location.hash.length > 0) {   
     s = parseInt(location.hash.replace('#',''),10);  
    } else { 
     s = 1; 
    } 
    main.showScreen(s); 
} 

我的屏幕更新代碼:

main.showScreen = function(i) { 
    // allow the back button to switch between screens 
    location.hash = i; 
    // but setting location.hash causes this same function to fire again! 
    // 
    // here follows the code that adds a new div with new text content 
    // ... 
} 

澄清:showScreen可以從應用程序的任何地方通過點擊「下一個」被調用,例如按鈕上的某個地方。

回答

0

在你main.showScreen功能,您可以:

if (location.hash != i) 
    location.hash = i; 

或者,你可以建立一個文件範圍的變量與最後的哈希值。

var lastHash = -1; 
window.onhashchange = function() { 
    var s; 
    if (location.hash.length > 0) {   
     s = parseInt(location.hash.replace('#',''),10);  
    } else { 
     s = 1; 
    } 

    if (lastHash != s) { 
     lastHash = s; 
     main.showScreen(s); 
    } 
}