How do i bind multiple events to several elements using the for loop in JS?
hai. I have been learning jS lately. How do i bind multiple events to several elements using a loop? Here is an example of what i am trying 开发者_开发问答to do. Lets say i have several divs with the ids $box1, #box2, #box3 ... #box9 etc. why doesnt this work? ( im using jquery ).
for (var i; i<8; i++){
$('#box' + i).click(function(){alert('hai')});
}
I know that i can do the same thing instead like this:
$('div').each(function(){
$(this).click(function(){alert('hai')});
});
However i d like to know why the first code snippet wouldnt work as i intended it to.
In javascript, simply defining a variable using var i;
doesn’t make it zero and "loopable".
So you simply need to assign a number to the i
variable.
for (var i = 0;
Also note that you can’t know what i
is inside the callback due to JavaScript closure.
精彩评论