0

I have a simple javascript that I'd like to loop for multiple elements. Here's my code:

<script type='text/javascript'>  
for(i = 1; i < 100; i++)
{
$('#link'+i).click(function() {
    $('#container').removeClass();
    $('#container').addClass('templateid'+i);
});
}
</script>

What I'd like to achieve is the same addClass function for multiple id's (e.g. link2, link3, link4), with the corresponding class (e.g. template2, template3, template4).

Any help would be hugely appreciated!

For reference, an individual call like this one, does work, so I don't see why the loop above doesn't function the same:

<script type='text/javascript'> 
$('#link2').click(function() {
    $('#container').removeClass();
    $('#container').addClass('templateid2');
});
</script> 
3
  • I guess 'container' and 'conatiner' is a typo and actually they are the same? Your code seem to be good now. Commented Feb 16, 2011 at 6:55
  • e.return false; wrong. use e.preventDefault(); return false; Commented Feb 16, 2011 at 7:01
  • Hmm fixed the spelling error, and was missing });. I actually realized that I don't need the return false call. But, still not working. Commented Feb 16, 2011 at 7:16

3 Answers 3

3

The problem here is that i inside the anonymous function for the on click handler, is a reference to the loops i and therefore will be 100 for all click handlers after the loop finished.

That a common "mistake" and requires a copy of i on every iteration of the loop in order to work correctly.

function createHandler(i) {
    $('#link'+i).click(function(e) {
         $('#container').removeClass();
         $('#container').addClass('template'+i); // this 'i' won't change anymore
        e.preventDefault();                      // thus the code will add the correct class
        return false;
    });
}

for(var i = 0; i < 100; i++) {
    createHandler(i); // one could also create a closure here
}

See: JavaScript Garden: Closures - Avoiding the Reference Problem.

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

Comments

0

Maybe you've forgotten to separate counter from string

$('#link[' + i + ']').click(function() {
    $('#templateid').removeClass();
    $('#templateid').addClass('templateid[' + i + ']');

2 Comments

OOps, yep, there is no need to use indexer, Nishant's answer is right.
Hi Danil, tried yours and Nishant's options but still no luck.
0

are you using prototype? $('#link') should return the element with id="link" and [i] further narrows it down to the attribute i.

if you want to use the variable i from the loop to find your link2, link3,.. try:

$('#link' + i).click { ...

also, your loop seems to be endless.

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.