我在js中向html添加了5个按钮,我希望将它们定义为延迟一秒,因此,当js到达addEventListener行时,这些按钮没有定义,并会给出一个错误.

enter image description here

Html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    <div id="btn-adder"></div>
    <script src="./script.js"></script>
</body>
</html>

Css:以下内容:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-size: 20px;
}
body{
    background: rgb(61, 61, 61);
}
#btn-adder{
    margin-top: 40px;
    text-align: center;
}
#btn-adder button{
    padding: 5px;
    margin: 5px;
}

JavaScript:如下所示:

const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
    setTimeout(function () {
        btnAdder.innerHTML += `<button id="btn${i}">Button ${i}</button>`;
    }, 1000);
}
for (let i = 0; i < 5; i++) {
    document.getElementById(`btn${i}`).addEventListener("click", function () {
        console.log(`Button ${i} clicked`);
    });
}

有没有办法让addEventListener识别新的变量?

推荐答案

是的,这是可能的,你甚至不需要第二个循环,这会减慢你的代码速度.(即使你可能不会注意到它)

Instead of adding the HTML directly to the btn-adder, you can create a new button and directly attach the eventlistener to it.

You can create a new HTML element with document.createElement() and then add all attributes, eventlisteners and everything else you need to the button.
Finally you'll add the newly created button with appendChild() as a new child element to your btn-adder element.

const btnAdder = document.getElementById("btn-adder");
for (let i = 0; i < 5; i++) {
    setTimeout(function () {
        // create button
        const buttonElement = document.createElement('button');
        buttonElement.id = `btn${i}`;
        buttonElement.textContent = `Button ${i}`
        
        // add eventlistener to the created button
        buttonElement.addEventListener("click", function () {
            console.log(`Button ${i} clicked`);
        });
        
        // add button to their parent
        btnAdder.appendChild(buttonElement);
    }, 1000);
}
*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-size: 20px;
}
body{
    background: rgb(61, 61, 61);
}
#btn-adder{
    margin-top: 40px;
    text-align: center;
}
#btn-adder button{
    padding: 5px;
    margin: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <title>Document</title>
</head>
<body>
    <div id="btn-adder"></div>
    <script src="./script.js"></script>
</body>
</html>

Javascript相关问答推荐

Bootstrap动态选项卡在切换选项卡后保持活动状态,导致元素堆叠

Plotly热图:在矩形上zoom 后将zoom 区域居中

togglePopover()不打开但不关闭原生HTML popover'

按下同意按钮与 puppeteer 师

在我的html表单中的用户输入没有被传送到我的google表单中

setcallback是什么时候放到macrotask队列上的?

为什么useState触发具有相同值的呈现

如何通过将实例方法的名称传递给具有正确类型的参数的继承方法来调用实例方法?

如何从HTML对话框中检索单选项组的值?

这个值总是返回未定义的-Reaction

TypeError:无法分解';React2.useContext(...)';的属性';basename';,因为它为空

使用js构造一个html<;ath&>元素并不能使其正确呈现

如何修复错误&语法错误:不能在纯react 项目中JEST引发的模块&之外使用导入语句?

与在编剧中具有动态价值的定位器交互

我怎样才能点击一个元素,并获得一个与 puppeteer 师导航页面的URL?

表单数据中未定义的数组键

Firefox的绝对定位没有达到预期效果

如何在单击Search按钮时更新Reaction组件?

已在EventListener中更新/更改异步的React.js状态对象,但不会导致组件重新呈现

JQuery-无法 Select 使用elementor添加的元素的值