0

我有一个 jquery 代码,它在我的图像上循环运行并一个一个地加载它们,除了将结果中的最后一个图像插入到“a”标签这一事实之外,一切都很好!这是我的代码(请查看“var a”......它应该在每个循环中以不同的方式插入变量“thissrc”:

$.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');

提前致谢!

伊兰。

4

2 回答 2

0

您应该可以data-imgsrc通过读回图像的 src 来设置,即:

'data-imgsrc': this.src

这将是可靠的,假设没有其他代码有机会在创建 img 之后和成功加载其初始 src 之前的短时间内更改 src。

如果这不是一个安全的假设,那么解决方案会稍微复杂一些,但一点也不罕见。

于 2013-06-08T19:49:30.310 回答
0

一个常见的错误。问题归结为:

for (var i = 0; i < countImages; ++i) {
    var thissrc = data[i].src;
    setTimeout(function() {
        // Will only ever alert the last value of thissrc
        alert(thissrc);
    }, 100);
}

在 JavaScript 中,for构造(或任何常规块语句)不会创建新的词法范围。也就是说,每次迭代都使用相同的变量 thissrc。上面的代码片段等价于:

var thissrc;
for (var i = 0; i < countImages; ++i) {
    thissrc = data[i].src;
    setTimeout(function() {
        alert(thissrc);
    }, 100);
}

事实上,var函数内的每个变量声明(使用)都作用于该函数

MDN 很好地解释了这个问题,并提供了一个使用额外功能的解决方案。在这种情况下,它可能看起来像:

$.get(url, function (data) {
    // ...
    for (var i = 0; i < countImages; ++i) {
        // ...
        var thissrc = data[i].src;
        // ...
        // Make a new callback for $.load using the *current* value of thissrc
        $.load(url, makeCallback(thissrc));
    }
    // ...

    function makeCallback(thissrc) {
        // Yes, this function returns another function
        return function() {
             // Do your callback stuff here
        };
    }
}

请注意,因为makeCallback $.get的回调函数中定义的,所以它可以访问所有这些局部变量,例如counterdescription。这些变量.makeCallback

JavaScript 1.7 使用let关键字使这更容易一些:

let允许您声明变量,将其范围限制为使用它的块、语句或表达式。这与var 关键字不同,关键字在全局范围内定义变量,或者在整个函数本地定义变量,而不管块范围如何。

这意味着您只需进行一项更改即可解决您的问题:

let thissrc = data[i].src;

不幸的是,由于这是一个相当新的添加,旧浏览器不支持它。

于 2013-06-08T19:52:33.733 回答