Reputation: 2032
Why does this code add class=hello5
to all the h2 elements upon being clicked? There are 4 h2 elements.
for (i=0; i < $('h2').length; i++) {
$('#' + i).click(function(index) {
$(this).addClass('hello' + i)
})
};
I want it to add class=hello0
, class=hello1
, etc.
HTML:
<h2 id="0">0</h2>
<h2 id="1">1</h2>
<h2 id="2">2</h2>
<h2 id="3">3</h2>
Do I have to add another loop? I'm confused. Thanks.
Upvotes: 0
Views: 106
Reputation: 5398
The main issue is that you are expecting the paramater for handler as index but it is not, it is eventObject.
You better to use .each() function like this:
$("h2").each(function(index, item){
$(item).click(function(e){
e.preventDefault();
$(this).addClass("hello" + index);
})
})
Upvotes: 1
Reputation: 298326
i
in your callback is the same i
that you're incrementing. By the time those callback functions are triggered, i
's value will be 8
, so all of the callbacks will add the same class.
Avoid creating event handlers in loops in general. It's much easier to just select those elements at once and add a single event handler to all of them:
$('h2').click(function() {
$(this).addClass('hello' + this.id);
});
Upvotes: 2
Reputation: 387
Because at the time click event is fire. Variable i
is finish loop and it get the value 4. The solution is use must get the index of h2
element and assign to class. I have a little bit change :
$().ready(function () {
for (i = 0; i < $('h2').length; i++) {
$('#' + i).click(function (index) {
$(this).addClass('hello' +$("h2").index( $(this)))
})
};
})
Upvotes: 0
Reputation: 17757
http://jsfiddle.net/Jbh3q/203/
$("h2").each(function(index,element){
$(element).addClass("hello" + index);
})
Upvotes: 0
Reputation: 2250
I edited your html snippet :
<h2 id="id0">0</h2>
<h2 id="id1">1</h2>
<h2 id="id2">2</h2>
<h2 id="id3">3</h2>
Try this code :
$('h2[id^="id"]').click(function(index){
var idx = $(this).index();
$(this).addClass('hello' + idx)
});
Upvotes: 0