Search code examples
jqueryjquery-loadjquery-get

Jquery: .load() with for loop, always takes the element


Im have a jquery code that running in loop over my images and load them one by one, All works fine beside the fact that it inserting to the 'a' tag the last image in results! Here is my code (Please take a look in "var a"... it should insert the variable 'thissrc' differently every loop:

$.get(url, function (data) {
    var countImages = data.length;
    console.log("count: " + countImages);
    var $ul = $('#thumbs').empty();
    var counter = 0;
    for (var i = 0; i < countImages; ++i) {
        try {
            var description = data[i].desc[0];
        } catch (e) {
            description = '';
        }
        if (description == undefined) description = '';
        var thissrc = data[i].src;
        console.log("ME: " + thissrc);
        $('<img width="' + screen.width / 2.4 + '" alt="' + data[i].alt + '" title="' + description + '"/>').load(function () {
            ++counter;
            var $this = $(this);
            var $li = $('<span/>', {
                className: 'pic'
            });
            var $a = $('<a/>', {
                href: '#',
                    'id': 'rel',
                    'data-inline': true,
                    'data-transition': 'slide',
                className: 'show-page-loading-msg',
                    'data-referrer': 'photo_container',
                    'data-imgsrc': thissrc
            });
            $ul.append($li.append($a.append($this)));
            if (counter == countImages) {
                $thumbscontainer.append($ul.show());
            }
        }).attr('src', data[i].src);

    }
}, 'json');

Thanks in Advance!

Eran.


Solution

  • You should be able to set data-imgsrc by reading back the image's src, ie :

    'data-imgsrc': this.src
    

    This will be reliable assuming no other code has had the opportunity to change the src in the short while after the img was created and before its initial src successfully loads.

    If this is not a safe assumption then the solution is somewhat more elaborate but not at all uncommon.