我知道我在这里做了一些非常愚蠢的事情.我得到错误document.getElementById()是null或不是对象.有人可以帮我这个吗?
<body>
<div id="box1" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box2" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box3" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box4" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box5" style="width:100px;height:100px;background:#ccc;"></div>
<script>
for (var i = 0; i < 5; i++) {
document.getElementById('box' + i).onclick = function() {alert('You clicked on box #' + i);};
}
</script>
</body>
Run Code Online (Sandbox Code Playgroud)
谢谢
索引问题
i正在开始0.没有名为的盒子box0.将循环更改为:
for (var i = 1; i <= 5; i++) {
document.getElementById('box' + i).onclick = function() {alert('You clicked on box #' + i);};
}
Run Code Online (Sandbox Code Playgroud)
范围问题
正如评论员所指出的那样,代码也存在范围问题.将其更改为:
for (var i = 1; i <= 5; i++) {
document.getElementById('box' + i).onclick = (function(index){
return function() {
alert('You clicked on box #' + index);
};
})(i);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
454 次 |
| 最近记录: |