开发者

jQuery returning the same element repeatedly inside of a for loop

开发者 https://www.devze.com 2023-03-25 03:23 出处:网络
I have a problem with the load function described below. For some reason even though I pass it a different parameter each time (I\'ve checked this with console.log(display)) it seems to return the sam

I have a problem with the load function described below. For some reason even though I pass it a different parameter each time (I've checked this with console.log(display)) it seems to return the same jQuery object.

I'm not sure if there is any other information I can provide, but let me know and I'll see what I can do.

// ...

function image(path, fn) {
    $(new Image()).load(function() {
        if (typeof fn === 'function') {
            fn($(this));
        }
    })
    .error(function () {
        console.error('Unable to load image: ' + imgBasePath + path);
    })
    .attr('src', imgBasePath + path);
}

function load(p, info, fn) {
    display = info || {
        Username : p.username,
        Lives : p.location,
        Supports : p.team,
        Level : p.level
    };

    image(p.avatar, function(img) {
        var detail = $('<div></div>', {
            class: 'player_details'
        });

        for (name in display) {
            detail.append($('<div>').html(name + ': ' + display[name]));
        }
        if (typeof fn === 'function') {
            fn(img, detail);
        }
    });
}

// ...

$.each(players, function(i, p) {
    var id,开发者_运维问答 elem;
    id = (player.sessionid === p.sessionid) ? 'me' : null;
    elem = $('<div />', {
        class: 'player clearfix',
        target: p.sessionid,
        id: id
    });
    load(p, {Username: p.username, Level: p.level}, function(img, details) {
        img.appendTo(elem);
        details.appendTo(elem);
    });
    elements.progress.append(elem);
});

// ...


I found the answer. display = info || {... was in the global scope because I didn't prepend it with var, changing it to var display = info || {... fixed the issue.

http://jsfiddle.net/tqKhA/8

0

精彩评论

暂无评论...
验证码 换一张
取 消