0

我坚持理解我的每个循环的行为。

这是我的代码:

$.each(thumbs, function() {    // where thumbs is array of strings
    project = this;

    $('#gallery').append(
        '<li>'
      + '<a href="/portfolio/' + project + '">'
      + '<img src="/img/' + project + '_bw.jpg" id="' + project + '_bw" />'
      + '<img src="/img/' + project + '_tn.jpg" id="' + project + '_tn" />'
      + '</a>'
      + '</li>'
    );

    // alert(project); - alerts every element of array as expected

    $('#' + project + '_bw').load(function() {

        // alert(project); - alerts only the last element of array, 
        // but as many times as many elements in array

        $('#' + project + '_bw').fadeIn(150,function(){
            $('#' + project + '_tn').css("opacity", 1);
        });
    });
});

问题是,当我试图定义元素的 id 时,我想在其中执行 .load 函数,它只将此函数附加到我正在循环的数组的最后一个元素。

4

1 回答 1

1

您的问题是在project每个循环之外定义的范围。

所以所有的thumbs都循环​​通过,并且设置了负载监听器。但是在调用第一个加载事件和调用加载侦听器函数时,该project变量被设置为循环的最后一个值。

所以你需要做的是在每个循环内设置一个局部变量来为每次迭代设置变量。

尝试这个:

Javascript

$.each(thumbs, function () {
    var thisProject = this;

    $('#gallery').append(
        '<li>' + '<a href="/portfolio/' + thisProject + '"><img src="/img/' + thisProject + '_bw.jpg" id="' + thisProject + '_bw" /><img src="/img/' + thisProject + '_tn.jpg" id="' + thisProject + '_tn" /></a></li>');

    $('#' + thisProject + '_bw').load(function () {
        $('#' + thisProject + '_bw').fadeIn(150, function () {
            $('#' + thisProject + '_tn').css("opacity", 1);
        });
    });
});

这是问题的一个例子:

HTML

<div id="output"></div>

Javascript

var count = 0;
$.each([500,1000,1500,2000,2500], function() {
    var thisValue = this;
    var inScopeCount = count + 1;
    setTimeout(function() {
        $('#output').append('<strong>For ' + thisValue + ':</strong><br />count: ' + count + '<br /> inScopeCount: ' + inScopeCount + '<br />');
    }, this);
    count += 1;
});

演示

于 2013-09-22T22:13:42.773 回答