简体   繁体   English

如何使用for循环将事件侦听器添加到动态生成的按钮

[英]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.

相关问题 如何动态添加事件监听器 - How add event listeners dynamically 动态添加事件监听器 - dynamically add event listeners Vanilla Javascript:如何将多个事件侦听器添加到使用 django 中的相同 class 动态创建的按钮? - Vanilla Javascript: How to add multiple event listeners to buttons which are dynamically created with same class in django? 事件监听器不能使用纯Javascript处理动态创建的按钮? - Event listeners not working with dynamically created buttons, using pure Javascript? 将事件侦听器添加到动态创建的按钮 - Adding Event Listeners to dynamically created buttons 如何在angularjs的for循环中动态创建$ rootScope。$ on事件侦听器 - How to dynamically create $rootScope.$on event listeners in a for loop in angularjs 向动态生成的按钮添加和删除活动类事件侦听器 - Add and remove active class event listener to dynamically generated buttons 通过for循环将事件监听器应用于按钮? - Apply Event Listeners to buttons via for loop? 未在动态生成的按钮中触发事件 - Event not triggered in dynamically generated buttons 如何将事件侦听器添加到从文件动态加载的SVG元素中? - How to Add Event Listeners to SVG Elements Loaded From File Dynamically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM