简体   繁体   中英

For loop won't pass i variable to Jquery function inside the loop

I've a for-loop and it won't pass it's i variable or any kind of a variable into Jquery function coded to run with every loop.

for (var i = 0; i < result.length; i++) {
    $('#frame-' + i + '').fadeOut(function () {
        ALERT(i);
        document.getElementById('frame-' + i + '').getElementsByTagName('img')[0].src = 'img/' + result.cat[i].id + '.png';

    });
    $('#frame-' + i + '').fadeIn();

}

I found that I can use .on or .bind functions but I've no idea how it should be done with fadeOut().

fadeOut.on() won't work.

Any suggestions to get this working?

Closure again!!!

$.each(result, function (i, res) {
    $('#frame-' + i + '').fadeOut(function () {
        alert(i);
        $(this).find('img').get(0).attr('src', 'img/' + res.cat.id + '.png');
    }).fadeIn();
})

The problem is by the time your fadeOut completes, the for loop has already completed and as such, the value of i that the fade code is reading, will always be the same (the last value).

Create a closure to pass the value of i . This gives you a local copy of i which won't be overwritten by the for loop. Also change ALERT() to alert() (Javascript is case sensitive).

for (var i = 0; i < result.length; i++) {
    (function(i){
        $('#frame-' + i).fadeOut(function () {
            alert(i);
            document.getElementById('frame-' + i + '').getElementsByTagName('img')[0].src = 'img/' + result.cat[i].id + '.png';

        }).fadeIn();
    })(i);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM