JavaScript全局变量在改变后会恢复到初始值

JavaScript global variable reverts back to original value after change?

本文关键字:恢复 全局变量 改变 JavaScript      更新时间:2023-09-26

我有一个全局变量window.current_index,记录应用程序状态,即我们在javascript web应用程序中的哪个页面。

然后我有一个代码块进入下一页,并增加window.current_index以反映状态变化(拿出不相关的DOM操作代码,只是会让它更难看到问题):

$('#next-page').click(function() {
    console.log('current index is ' + window.current_index);
    var next_index = window.current_index + 1;
    console.log('next index is ' + next_index);
    //update the index
    window.current_index = window.current_index + 1;
    console.log('current index is now ' + window.current_index);
});

它第一次工作得很好,但是当我再次单击它时,我没有得到预期的结果。使用控制台日志记录,我得到一个奇怪的输出:

current index is 2         main.js:57
next index is 3            main.js:59
current index is now 3     main.js:62
current index is 2         main.js:57
next index is 3            main.js:59
current index is now 3     main.js:62

似乎window.current_index 没有更新,当我再次启动功能,即使它说它是以前?是不是这个变量的适当范围,以便我可以存储在它的应用程序状态,它将持续整个事件处理程序调用?显然不行,因为它不起作用了……我做错了什么?我猜这是一个范围问题,但我不能为我的生活弄清楚我将如何正确地做它……:/

澄清:这里没有页面重新加载,页面不会在操作之间重新加载。我只是通过JavaScript隐藏/显示显示一个新的"框架"。我也不使用iframes,我只是在一个单页网站上使用$('div').hide()$('div').show()

我可以用

window.current_index = 0;
$('#next-page').click(function() {
    console.log('current index is ' + window.current_index);
    var next_index = window.current_index + 1;
    console.log('next index is ' + next_index);
    //update the index
    window.current_index = window.current_index + 1;
    console.log('current index is now ' + window.current_index);
});
http://jsfiddle.net/hHFkJ/1/

这段代码没有任何问题。我有两个具有相同选择器的事件处理程序,这导致了问题。感觉傻…