带参数的动态addEventListener

时间:2018-03-25 01:08:33

标签: javascript onclick addeventlistener

我试图将名称插入到输入元素的值中。我试图将玩家[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);
};

1 个答案:

答案 0 :(得分:1)

问题是使用关键字i

声明的变量var
  

使用var声明的变量的范围是其当前执行上下文,因此,变量i将使用最后一个值结束for-loop

&#13;
&#13;
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;
&#13;
&#13;

另一种方法是使用语句let

声明该变量
  

let声明的变量的范围是定义它们的块,以及任何包含的子块。这样,let非常像var。主要区别在于 var变量的范围是整个封闭函数

&#13;
&#13;
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;
&#13;
&#13;

另一种方法是使用 IIFE 返回具有特定值/播放器的函数。

&#13;
&#13;
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;
&#13;
&#13;