Reputation: 17
I have divs with numbered ids that I want to process on the click event:
$(function() {
for (var i = 1; i != 10; ++i) {
$("#div" + i).live('click', function () {
//...
console.log(i); // always prints 10
});
}
});
// html
<div id="div1">...</div>
<div id="div2">...</div>
etc.
I was expecting that a click event on each div will fire its own event handler. But that is not the case.
Any fix please.
Upvotes: 0
Views: 185
Reputation: 1900
$(function() {
$("div[id^=div]").click( function(){
var id = $(this).attr('id').replace('div', '');
console.log(id);
});
});
I find this way of checking for clicks to be much more compact and easier, heres a working fiddle as well, although there are already answers for why your i variable is sticking so feel free to use which ever method seems appropriate.
Upvotes: 0
Reputation: 369
The loop is holding the last value because the live event is called after the loop has finished. You need to pass the value to the live event within the loop, as follows:
$(function() {
for (var i = 1; i != 10; ++i) {
$("#div" + i).live('click', {i: i}, function (e) {
//...
console.log(e.data.i); // prints correct value
});
}
});
Upvotes: 0
Reputation: 74420
Using a closure:
$(function () {
for (var i = 1; i < 11; i++) {
(function (i) {
$("#div" + i).live('click', function () {
//...
console.log(i); // always prints 10
});
}(i));
}
});
But depending your jquery version, you could use instead .on() (delegation) or .delegate() method using as selector: '[id^=div]'
Upvotes: 1