How to use variable value during declaration in anonymous JavaScript function?

This is really a basic question, but ...

I have 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 the images on 'blah.jpg'when clicked. Similarly, pressing div with id ="blah1"should change all images to 'ha.jpg'.

However, the anonymous function will not work, because it will use the value "i" at runtime, that is 2. This means that pressing either div will try to set all images to arr [2] - a nonexistent element (it is interesting not to throw a JS error to my car, and another story ...).

How can I create an anonymous function using the value 'i' during declaration?

As a simpler example:

for (var i=0; i<10; i++)
{
    $('div#blah'+i).click(function() {
       alert(i)); });
}

"blah1" .. "0", "blah0", "1".

"10", , "" .

+3
4

, , :

function makeClickHandler(arr, local_i) {
    return function() {
        $('img').attr('src', arr[local_i]);
    };
}

var arr = Array('blah.jpg','ha.jpg');
for (var i=0; i<array.length; i++)
{
    $('div#blah' + i).click(makeClickHandler(arr, i));
}

local_i, .

+5

:

for (var i=0; i<10; i++)
{
    (function(j){
        $('div#blah'+j).click(function() { alert(j)); });
    })(i);        
}

(function(){ /* code */ })() , , , .

+4

.


var j = 0;
for (var i=0; i<array.length; i++)
{
    $('div#blah' + j).click(function() {
           $('img').attr('src', arr[i]); });

    j++;
}

0

, :

var arr = Array('blah.jpg','ha.jpg');
for (var i=0; i<array.length; i++)
{
    eval("$('div#blah' + i).click(function() { $('img').attr('src', arr[" + i + "]); })");
}

:

for (var i=0; i<10; i++)
{
    eval("$('div#blah'+i).click(function() { alert(" + i + ")); });");
}
0
source

All Articles