我在 js 中向 html 添加了 5 个按钮,我希望它们以一秒的延迟定义,并且由于这个 js,当它到达 addEventListener 行时,这些按钮未定义并给出错误。
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 识别新变量?
最佳答案
是的,这是可能的,您甚至不需要第二个循环,这会减慢您的代码速度。 (即使你可能不会注意到它)
您可以创建一个新按钮并直接将事件监听器附加到它,而不是直接将 HTML 添加到 btn-adder
。
您可以使用 document.createElement() 创建一个新的 HTML 元素然后将所有属性、事件监听器和您需要的所有其他内容添加到按钮。
最后,您将使用 appendChild() 添加新创建的按钮作为 btn-adder
元素的新子元素。
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 - 有没有办法在addEventListener中使用js写的html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74486902/