Currently I’m working on a project using RaphealJS library and everything seems to be alright until I encountered a problem like this.
Instead of doing this multiple times :
dolphinIcon[1].click(function() {
this.attr({
stroke: 'black', 'stroke-width': 2,
fill: 'green'
});
alert(1);
});
dolphinIcon[2].click(function() {
this.attr({
stroke: 'black', 'stroke-width': 2,
fill: 'green'
});
alert(2);
});
dolphinIcon[3].click(function() {
this.attr({
stroke: 'black', 'stroke-width': 2,
fill: 'green'
});
alert(3);
});
Why can’t I just do this ?
for(var i=0; i<dolphinIcon.length; i++){
dolphinIcon[i].click(function() {
this.attr({
stroke: 'black', 'stroke-width': 2,
fill: 'green'
});
alert(i);
});
}
I just want each icon which is stored in the array to alert() the number of its index, but when I use for-loop, it always alert() the same number(size of the array) no matter which icon I clicked on. How should I fix this ?
This is a classic JavaScript problem. The variable
iin each callback function is the same one, which will bedolphinIcon.lengthonce the loop is done.You need to use a closure to “capture” the
ivariable.clickFuncwill return a function that “closes” on the value ofi.You can also pass extra data to the
clickhandler, to be used once it’s called.