如何使用for循环将事件侦听器添加到动态生成的按钮 [英] How to add event listeners using a for loop to dynamically generated buttons

查看:91
本文介绍了如何使用for循环将事件侦听器添加到动态生成的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有动态生成按钮的页面,我正在尝试使用for循环向其添加事件监听器。
我不确定我的代码为什么不起作用,因为它通过其ID引用每个按钮并使用点表示法添加事件监听器。代码中有一些注释可帮助澄清。

I have a page w/ dynamically generated buttons and i'm trying to add event listeneners to them using a for loop. 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. 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>

这里是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
    }
}

如何使用一个for循环?到动态生成的按钮?

How would this be done using a for loop? to dynamically generated buttons?

推荐答案

addEventListener 是在元素上找到的方法。

addEventListener is a method you find on elements.

rollDiceBtns [i] 是一个元素。

rollDiceBtns [i] .id 是字符串。

删除 .id

这篇关于如何使用for循环将事件侦听器添加到动态生成的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆