这不是重复的问题。
我有一个按钮列表,当它被动态生成时,我希望传递一个唯一的值,如下所示。
预期结果:我希望警报显示"Hello World“加上按钮索引时,它是生成的。
当前结果: alert不断显示"Hello World 20“。20是for循环的最后一个索引。
<!DOCTYPE html>
<html>
<body onload="genManyBtns()">
<p>Click the button to show an Alert Corresponding to it's Index</p>
<script>
function genManyBtns() {
for (var i = 0; i < 20; i++) {
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
btn.onclick = function() {
alert("Hello World " + i)
};
document.body.appendChild(btn);
}
}
</script>
</body>
</html>
发布于 2019-04-08 00:47:39
您正在使用普通的JavaScript。为了使用索引,您可以将其保存在属性中。我创建了一个data-index-button属性,以便在按钮被单击时获取它并使用它来显示按钮的索引。
function genManyBtns() {
for (var i = 0; i < 20; i++) {
var btn = document.createElement("BUTTON");
btn.setAttribute("data-index-button", i);
btn.innerHTML = "CLICK ME";
btn.onclick = function() {
var index_button = this.getAttribute("data-index-button");
alert("Hello World " + index_button);
};
document.body.appendChild(btn);
}
}发布于 2019-04-08 01:15:41
您必须为button onclick编写另一个方法。我只是用clickMe()方法更新你的代码。试试这个,我希望它能帮到你。谢谢
<!DOCTYPE html>
<html>
<body onload="genManyBtns()">
<p>Click the button to show an Alert Corresponding to it's Index</p>
<script>
function genManyBtns() {
for (var i = 0; i < 20; i++) {
var btn = document.createElement("BUTTON");
btn.innerHTML = "CLICK ME";
btn.className = "clickMe";
btn.setAttribute('data-index', i);
document.body.appendChild(btn);
}
}
document.addEventListener('click', function (e) {
if (e.target.matches('.clickMe')) {
e.preventDefault();
alert("Hello World " + e.target.dataset.index);
}
}, false);
</script>
</body>
</html>
https://stackoverflow.com/questions/55561324
复制相似问题