当循环停止案例增加1时,页面停止加载

时间:2019-07-18 14:28:56

标签: javascript html

我在网站上使用Instagram API,并且只需要抓住前8张图片描述的前几个字即可。

我的问题是,如果每张图片尝试使用11个以上的单词,该页面将停止加载。

这是我的代码:


success: function (data) {
            console.log(data);
            data.data.forEach(function (pic) {
                var height = pic.images.standard_resolution.height;
                var width = pic.images.standard_resolution.width;
                if (width == height && pic.type != "video") {
                    $("#img" + i).append("<img class='img-fluid' alt='placeholder' src=\"" + pic.images.standard_resolution.url + "\" > ");
                    var text = pic.caption.text;
                    var s = ""
                    var words = 0;
                    var j = 0;
                    while (words < 11 || j < text.length) {
                        if (text[j] == ' ') {
                            words++;
                        }
                        s += text[j];
                        j++;
                    }
                    $("#img" + i).append("<div class='mask flex-center waves-effect waves-light rgba-black-light'><p id='txt" + i + "' class='white-text'>" + s + "</p></div>");
                    i++;
                }
            });
        }

我真的不知道我在做什么错,再加上8个字(我只获取8张图片)可能会如此可怕。

预先感谢您解决我的问题。

1 个答案:

答案 0 :(得分:2)

您的while条件应使用 && 而不是 || ,例如while (words < 11 && j < text.length),否则您可能会到达句子的结尾但仍未达到最大字数。另外,您在var s = "";

上缺少分号

要简化代码,可以使用split方法来获取短语的单词数。例如:

var str = 'This is a random string';
var wordCount = str.split(' ').length;
相关问题