[英]How to add event listeners using a for loop to dynamically generated buttons
I have a page w/ dynamically generated buttons and i'm trying to add event listeneners to them using a for loop. 我有一个页面w /动态生成的按钮,我试图使用for循环向它们添加事件侦听器。 I'm not sure why my code is not working as it refers the each button via it's ID and uses dot notation to add the event listener.
我不确定为什么我的代码不起作用,因为它通过其ID引用每个按钮并使用点表示法添加事件侦听器。 There is some commenting in the code to help clarify.
在代码中有一些注释可以帮助澄清。
Here is abbreviated markup showing the buttons only 这是仅显示按钮的缩写标记
<button class="btnRollDice" id="btnRollDiceP1">Roll Dice!</button>
<button class="btnRollDice" id="btnRollDiceP2">Roll Dice!</button>
<button class="btnRollDice" id="btnRollDiceP3">Roll Dice!</button>
Here is the js 这是js
rollDiceBtns = document.getElementsByClassName('btnRollDice');//returns a HTML collection
function addEventListeners(){
console.log(rollDiceBtns);
for(i=0;i<rollDiceBtns.length;i++){
console.log(rollDiceBtns[i].id); //THIS WORKS,
rollDiceBtns[i].id.addEventListener('click', rollDice, false); //THIS DOES NOT
}
}
How would this be done using a for loop? 使用for循环该怎么做? to dynamically generated buttons?
动态生成的按钮?
addEventListener
is a method you find on elements. addEventListener
是在元素上找到的方法。
rollDiceBtns[i]
is an element. rollDiceBtns[i]
是一个元素。
rollDiceBtns[i].id
is a string. rollDiceBtns[i].id
是一个字符串。
Remove .id
. 删除
.id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.