我正在尝试创建一个循环,它将显示一些图像并为每个图像添加一个事件监听器,单击该图像时会为humanGoal分配适当的值。我有:
var humanGoal;
function displayPicker(round){
for(var i = 0; i <= round; i++){
document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
document.getElementById('picker'+i).addEventListener("click", function () {
humanGoal = i;
document.write('you picked ' + humanGoal );
});
}
}
为什么humanGoal总是=== round + 1,而不是for循环中的变量i?
答案 0 :(得分:1)
humanGoal
变量正在被每个for
循环迭代覆盖,并在结尾处保存round
+ 1值。说不同的话 - 它总会显示错误的索引。
解决方案:将同一个类应用于每个img
元素,绑定click
事件侦听器并通过在{{1}内传递index
变量来显示实际i
功能。
Array#forEach
答案 1 :(得分:0)
看到你的问题的答案很简单,当你试图用i的值分配人类目标时,循环已经被迭代过了#34; rounds&#34;这就是为什么你总是在点击功能中获得 i === round 的价值。
请参阅以下代码段
<html>
<script>
var humanGoal;
function displayPicker(round){
for(var i = 0; i <= round; i++){
document.write('<img src=img/die' + i + '.png id="' + 'picker' + i + '">');
document.getElementById('picker'+i).addEventListener("click", function () {
console.log("me getting called second");
humanGoal = i;
document.body.append('you picked ' + humanGoal );
});
console.log("me getting called first");
}
}
</script>
<body onload="displayPicker(4)">
</body>
</html>
&#13;
为了获得正确的结果,您可以遵循@Kind用户提供的方法