dynamic onClick not working
I know im doing something really really stupid here.Im getting the error document.getElementById() is null or not an object. Could some one please help me with this?
<body>
<div id="box1" style="width:100px开发者_JAVA百科;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>
Thank You
Indexing Issue
i
is starting on 0
. There is no box called box0
. Change loop to:
for (var i = 1; i <= 5; i++) {
document.getElementById('box' + i).onclick = function() {alert('You clicked on box #' + i);};
}
Scope Issue
As pointed out by commentators, there is also a scope issue with the code. Change it to:
for (var i = 1; i <= 5; i++) {
document.getElementById('box' + i).onclick = (function(index){
return function() {
alert('You clicked on box #' + index);
};
})(i);
}
I believe already got solution; anyway I just want to say that you have jQuery alternative too..
$(document).ready(function() {
$("div[id*=box]").click(function() {
alert('You clicked on box ' + $(this).attr('id'));
});
});
精彩评论