0

Example is this and this is not working. What is my mistake ?

var i=1;
for(i; i <=165; i++){
    jQuery(".tekAlan"+i).click(function() {   
    jQuery(".tekAlan"+i).addClass("tekAlanSecildi");    
    });
}

Thanks.

3 Answers3

6

You're passing i by reference, not by value, so i isn't referring to the number that you think it is after your loop runs. Take a look at this simple example to see what I mean.

In this case, you can probably just use an attribute selector and this:

jQuery('[class^="tekAlan"]').click(function() {   
    jQuery(this).addClass("tekAlanSecildi");    
});

If you want to fix your current code, you'll have to shadow i with an anonymous function:

for(var i = 1; i <= 165; i++){
    (function(i) {
        jQuery(".tekAlan" + i).click(function() {   
            jQuery(".tekAlan" + i).addClass("tekAlanSecildi");    
        });
    })(i);
}
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Awesome example of shadowing variables. I was also wondering how to solve it without using "this", and your code does the trick. – ashiina Jan 13 '13 at 01:36
  • are you sure only `.tekAlan165` will be clickable? I think all of them will receive the click event, but, again, all of them will add the class to the last one – Sergi Juanola Jan 13 '13 at 01:37
0

I guess you want to add to only the clicked item the class. However, it always adds the class to the last one. That's because i is accessed after the end of the for, so it always contains 165. Do this to solve your problem:

var i=1;
for(i; i <=165; i++){
    jQuery(".tekAlan"+i).click(function() {   
        jQuery(this).addClass("tekAlanSecildi");    
    });
}

jQuery(this) is a reference of the element affected by the event (in this case, click)

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93
0

Although this is not very clear, you could try something like this

1) add a class to all of your elements

2)

$('.someclass').click(function(){

    $(this).addClass('someotherclass');

})

you dont need a for loop.

0x_Anakin
  • 3,229
  • 5
  • 47
  • 86