我试图获得按钮ID,但它没有 - 它是关于范围?

时间:2016-03-21 07:23:56

标签: javascript

每次点击都会得到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>

1 个答案:

答案 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);
}