while循环不能使用$ .each

时间:2012-03-01 10:05:00

标签: javascript jquery arrays json

this page我试图限制显示的图像数量。我尝试了以下操作,但它不断崩溃。

while (screenshots.length < 5) {
    $.each(images, function (i, el) {
                    startHTML += "<a href=\"" + link + "\" title=\"" + title + "\">";
                    startHTML += "<img src=\"" + el + "\" alt=\"\" width=\"200px\" height=\"200px\">";
                    startHTML += "</a>";
                });
}

图像从json中拉出来..完整代码:

var screenshots = $('#recent-screenshots span');



       // get screenshots we can pass limit here if we want
        $.getJSON("gallery/getScreenshots.php", function (data) {
            var startHTML = "";
            $.each(data, function (i, image) {
                var link = image.link;
                var title = image.title;
                var images = image.images;

                $.each(images, function (i, el) {
                    startHTML += "<a href=\"" + link + "\" title=\"" + title + "\">";
                    startHTML += "<img src=\"" + el + "\" alt=\"\" width=\"200px\" height=\"200px\">";
                    startHTML += "</a>";
                });


            });
            screenshots.html(startHTML);

        });
    });

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

这是一个无限循环:

while (screenshots.length < 5) {
    $.each(images, function (i, el) {
                    startHTML += "<a href=\"" + link + "\" title=\"" + title + "\">";
                    startHTML += "<img src=\"" + el + "\" alt=\"\" width=\"200px\" height=\"200px\">";
                    startHTML += "</a>";
                });
}

while循环的条件涉及screenshots.length,但是你永远不会在while循环中修改那个值,所以如果条件最初是真的,它会在while循环中永远保持为真。

您可以通过手动迭代图像来修复它,只需执行较小的长度或5。

for (var i = 0, len = Math.min(images.length, 5); i < len; i++) {
    startHTML += "<a href=\"" + link + "\" title=\"" + title + "\">";
    startHTML += "<img src=\"" + images[i] + "\" alt=\"\" width=\"200px\" height=\"200px\">";
    startHTML += "</a>";

}

答案 1 :(得分:1)

你没有递减/递增控制我认为的循环的变量。你可以试试像

这样的东西
var maxNumber = screenshots.length, c = 0;
while (c  < maxNumber) {
    $.each(images, function (i, el) {
                    startHTML += "<a href=\"" + link + "\" title=\"" + title + "\">";
                    startHTML += "<img src=\"" + el + "\" alt=\"\" width=\"200px\" height=\"200px\">";
                    startHTML += "</a>";
                });
      c++;
}