Bind click to control
count=1;
for(var i=0;i<5;i++){
count++;
$("#ImageProductLeft"+count.toString()).bind('cl开发者_C百科ick', function(){
alert(i);
});
}
I want that when click on ImageProductLeft1
show alert(1)
and click on ImageProductLeft2
show alert(2)
and ...
But onclick
on all ImageProductLeft1
show alert(5)
.
This is bit more elegant and flexible:
$("div[id^='ImageProductLeft']").each(function(index) {
$(this).click(function() {
alert(index);
});
});
You can have as much elements starting with ImageProductLeft
as you want, and clicking any will alert their respective index.
Live test case.
You are creating a function in a a loop (closures). All variables will be shared between them, also i
.
When the functions are called eventually, the loop already finished and i
will have the value 5
.
JavaScript does not have block scope. To create a new scope and capture the value of the variables you make a function call:
for(var i=0;i<5;i++){
(function(x) {
$("#ImageProductLeft"+count.toString()).bind('click', function(){
alert(x);
});
}(i));
}
Here we use an immediate function to "capture" the value of i
.
That said, as you are using jQuery, there are other, more elegant methods to solve this, as shown in @scessor's and @Shadow Wizard's answers.
Nevertheless, it is important to know why it works like this and how it can be solved in "pure" JavaScript.
Closures can be tricky. I suggest having a look at JavaScript Closures for Dummies.
count=1;
for(var i=0;i<5;i++){
count++;
$("#ImageProductLeft"+count.toString()).bind('click', {i: i}, function(event){
alert(event.data.i);
});
}
for (var i = 1; i<6; i++)
{
$("#ImageProductLeft" + i.toString()).bind('click', function() {
alert(i);
});
}
You're having this problem because the i
in each of the event handlers you created is pointing to the same location in memory. Try using this:
count=1;
for(var i=0;i<5;i++){
count++;
$("#ImageProductLeft"+count.toString()).bind('click',
function(x){
return function() { alert(x); };
}(i)
});
}
This is a rather common mistake. See this page for further explanation
精彩评论