1

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.

1
  • 1
    As a side note, creating functions within a loop is not a good idea. You should declare the function as a variable before the loop. Better yet, you should define a common class for all the elements that have the same onclick behaviour and use a class selector instead. Commented Feb 20, 2011 at 20:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.