【发布时间】:2012-03-02 20:56:26
【问题描述】:
我会很快,直接跳到案子。代码已注释,因此您知道我的意图。基本上,我正在构建一个基于 HTML5 的小型游戏,而不是将内容保存在服务器上或 cookie 中,我只会为玩家提供关卡代码。当玩家将代码(以简单哈希的形式)输入文本输入字段并单击按钮加载该级别时,函数“l”被调用。该函数首先检索玩家的条目,然后遍历哈希列表并比较它们。喜欢比赛时,应该加载某个级别,但出现错误。我做了一点调试,发现迭代器(“i”)的值在 setTimeout 内发生了变化!我想暂停 1 秒,因为立即加载关卡太快而且看起来很糟糕。
levelCodes = //Just a set of "hashes" that the player can enter to load a certain level. For now, only "code" matters.
[
{"code": "#tc454", "l": 0},
{"code": "#tc723", "l": 1},
]
var l = function() //This function is called when a button is pressed on the page
{
var toLoad = document.getElementById("lc").value; //This can be "#tc723", for example
for (i = 0; i < levelCodes.length; i++) //levelCodes.length == 2, so this should run 2 times, and in the last time i should be 1
if (levelCodes[i].code == toLoad) //If I put "#tc723" this will be true when i == 1, and this happens
{
console.log(i); //This says 1
setTimeout(function(){console.log(i)}, 1000); //This one says 2!
}
}
【问题讨论】:
-
不错的评论,请大家点赞。
-
仅供参考,您的代码由于多种原因没有通过 jslint,并且会在某些浏览器中产生错误
-
@MarkSchultheiss,请解释一下,我认为 jsLint 是某种评估器,对吗?那么,你能告诉我为什么不计算吗?
-
可能最简单的方法是查看:jsfiddle.net/h9tNJ - 单击 jslint 按钮。 - 注意额外的逗号肯定会在 IE 中导致错误。
-
哦,我明白了。这也是一个非常有用的工具!我通常会把所有的东西都放进去,我会小心的,我想这只是一个例外......
标签: javascript html variables settimeout