我试图将名称插入到输入元素的值中。我试图将玩家[i]作为函数addPlayer的参数传递,但它表示未定义。当我点击每个名字时,它应该将它传递给输入字段。我在哪里失败?
var players = ["john","doe"];
function addPlayer(str) {
console.log(str);
document.getElementsByClassName("answerInput")[0].value += str;
}
for (var i = 0; i < players.length; i++) {
var node = document.createElement("div");
var textnode = document.createTextNode(players[i]);
node.appendChild(textnode);
node.classList.add("newPlayers");
document.getElementById("pushPlayer").appendChild(node);
node.addEventListener('click', function () {
addPlayer(players[i]);
}, false);
};
答案 0 :(得分:1)
问题是使用关键字i
var
使用
var
声明的变量的范围是其当前执行上下文,因此,变量i
将使用最后一个值结束for-loop
。
var players = ["john (click me)", "doe (click me)"];
for (var i = 0; i < players.length; i++) {
var node = document.createElement("div");
var textnode = document.createTextNode(players[i]);
node.appendChild(textnode);
node.classList.add("newPlayers");
document.getElementById("pushPlayer").appendChild(node);
node.addEventListener('click', function() {
console.log(i)
}, false);
};
&#13;
<div id='pushPlayer'>
</div>
&#13;
另一种方法是使用语句let
let
声明的变量的范围是定义它们的块,以及任何包含的子块。这样,let
非常像var
。主要区别在于var
变量的范围是整个封闭函数。
var players = ["john", "doe"];
function addPlayer(str) {
console.log(str);
document.getElementsByClassName("answerInput")[0].value += str;
}
for (let i = 0; i < players.length; i++) {
var node = document.createElement("div");
var textnode = document.createTextNode(players[i]);
node.appendChild(textnode);
node.classList.add("newPlayers");
document.getElementById("pushPlayer").appendChild(node);
node.addEventListener('click', function() {
addPlayer(players[i]);
}, false);
};
&#13;
<input class='answerInput' placeholder='Enter answer'>
<div id='pushPlayer'>
</div>
&#13;
另一种方法是使用 IIFE 返回具有特定值/播放器的函数。
var players = ["john", "doe"];
function addPlayer(str) {
console.log(str);
document.getElementsByClassName("answerInput")[0].value += str;
}
for (var i = 0; i < players.length; i++) {
var node = document.createElement("div");
var textnode = document.createTextNode(players[i]);
node.appendChild(textnode);
node.classList.add("newPlayers");
document.getElementById("pushPlayer").appendChild(node);
node.addEventListener('click', (function(player) {
return function () {
addPlayer(player);
}
})(players[i]), false);
};
&#13;
<input class='answerInput' placeholder='Enter answer'>
<div id='pushPlayer'>
</div>
&#13;