Hi,
This is a really basic question but...
I have some code like this
var arr = Array('blah.jpg','ha.jpg');
for (var i=0; i<array.length; i++)
{
$('div#blah' + i).click(function() {
$('img').attr('src', arr[i]); });
}
This should bind the div with id="blah0"
to change all images to 'blah.jpg'
when clicked.
Similarly, clicking the div with id ="blah1"
should change all images to 'ha.jpg'
.
However, the anonymous function won't work because it will use the value of 'i' at the time of execution, i.e. 2. This means that clicking either div will try and set all images to arr[2] - a non-existent element (interestingly not throwing a JS error on my machine but that's another story...).
How can I get the anonymous function to be created using the value of 'i' at declaration time?
As a simpler example:
for (var i=0; i<10; i++)
{
$('div#blah'+i).click(function() {
alert(i)); });
}
This should display '0' when I click 'blah0', '1' when I click 'blah1' etc.
However, by default it will display '10' no matter which 'blah' i click.