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.
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.
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);
}
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
)
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.