无法突破javascript for循环

时间:2013-11-03 16:44:52

标签: javascript jquery loops for-loop break

我无法摆脱for循环。

现在,循环在每个页面上执行jQuery getJSON调用。如果页面包含数据,则会记录所有项目。如果页面没有数据,则循环应该完全停止。

然而,无论何时我运行它,它都会遍历所有100页。一旦点击没有数据的页面,它会记录“此页面没有内容”,但继续运行for循环。 (因此,在我的控制台中,“这个页面没有任何内容”的结尾源源不断)

我做错了什么?

我想避免抛出i = NOTANINTEGER来停止循环

for (var i=0; i< 100; i++)
  {
    var breakForLoop = false;
    var API = "http://www.foo.com/bar.json?page=" + i;

    $.getJSON(API,  function(data) {
      var items = {};
      // logs items from page run only when the page has data
      if (data.length > 0) {
        $.each( data, function(i, item) {
          console.log(item.text);
        });
      }
      // the page has no data, therefore remainder pages have no data too
      else {
        console.log("this page has no content");
        breakForLoop = true;
        return;
      }
    });

   if (breakForLoop) {
       break;
   }
}

1 个答案:

答案 0 :(得分:3)

一种可能的解决方案是使用

之类的东西
//this method tries to fetch data from page `x`, if there is data in the current page then it will again try to fetch data from page `x + 1`
function fetchData(page) {
    page = page || 0;
    var API = "http://www.foo.com/bar.json?page=" + page;

    $.getJSON(API, function (data) {
        var items = {};
        // logs items from page run only when the page has data
        if (data.length > 0) {
            $.each(data, function (i, item) {
                console.log(item.text);
            });
            //since there is data in the current page try to fetch data from page page + 1
            fetchData(page + 1);
        }
        // the page has no data, therefore remainder pages have no data too
        else {
            console.log("this page has no content");
        }
    });
}

//initiage fetching data
fetchData(0) ;