我在javascript中使用location.hash,允许用户在ajax屏幕之间切换(在同一个html页面中动态添加和删除的div)。
问题是,当我通过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,例如,通过单击页面上的“下一步”按钮。
发布于 2013-11-26 12:16:16
在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);
}
}
https://stackoverflow.com/questions/20216274
复制