感谢你们优秀的 Overflowians 的帮助,我修复了我愚蠢的小 RNG 加法游戏并让它运行起来。现在,根据一位用户的建议,在编写下一个游戏之前,我尝试将加法游戏代码的范围从全局更改为本地;我希望每个游戏都完全包含在自己的范围内,因为我知道学会不轻率地污染全局范围是一个好主意。但是,我对如何实现这一目标有点困惑。
以下是当前功能加法游戏的代码:
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
这是我尝试包装它的尝试,这只成功地破坏了游戏,使得按钮甚至没有响应:
window.addEventListener("load", function() {
function beginAdditionChallenge() {
var x = Math.ceil(Math.random()*100);
alert(x);
for (var i = 0; i < 3; i++) {
var a = Number(prompt("Provide the first addend.", ""));
var b = Number(prompt("Provide the second addend.", ""));
if (a + b === x) {
alert("Well done!");
break;
}
else if (a + b !== x && i < 2) {
alert("Please try again.");
}
else {
alert("Derp.");
}
}
}
function initChallenge() {
var button = document.getElementById("challengeButton");
button.addEventListener("click", beginAdditionChallenge);
}
window.addEventListener("load", initChallenge);
});
功能代码可在 JSFiddle here 上获取.
最佳答案
请注意,JSFiddle 中的 onLoad
选项与第二个代码段的作用相同。当您自己绑定(bind)到'load'
时,您需要选择Nowrapped
选项之一。
并且,问题源于尝试在 'load'
处理程序中绑定(bind)到 'load'
:
window.addEventListener("load", function() {
// ...
window.addEventListener("load", initChallenge);
});
当事件已经触发并处理外部绑定(bind)时,向其添加更多处理程序为时已晚。它们不会被循环,并且该事件不应再次发生。
您可能需要在外部事件绑定(bind)中调用 initChallenge
:
window.addEventListener("load", function() {
// ...
initChallenge();
});
或者,您可以使用 IIFE与内部绑定(bind):
(function () {
// ...
window.addEventListener("load", initChallenge);
})();
关于javascript - 将范围从全局更改为局部破坏 Javascript 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24226660/