每次点击都会得到4个不是预期的按钮:它是关于范围的吗?
<button id="button-1">one</button>
<button id="button-2">two</button>
<button id="button-3">three</button>
<p>Then you assign click event handlers in a loop: </p>
<script>
for (var i = 1; i <= 3; i++) {
// alert(i);
document.getElementById('button-' + i).onclick = function(){
alert("This is button: " + i);
};
}
</script>
答案 0 :(得分:1)
您必须使用let
,
for (let i = 1; i <= 3; i++) {
document.getElementById('button-' + i).onclick = function(){
alert("This is button: " + i);
};
}
或者每次迭代创建一个范围
for (var i = 1; i <= 3; i++) {
(function(i) {
document.getElementById('button-' + i).onclick = function(){
alert("This is button: " + i);
};
})(i);
}