繁体   English   中英

jQuery $ .each通过数组

[英]Jquery $.each through array

我正在使用此代码循环遍历数组,并为每个value调用函数doAjax()

$.each(categories, function(index, value){
        doAjax(value);
});

函数doAjax()将进行Ajax调用,并将一些数据附加到html页面。 问题是,当我遍历大型数组(超过10个索引)时,这会导致我的网站崩溃。

我认为可以解决此问题的唯一方法是使听众像这样的页面:

$(window).scroll(function(){
     if($(window).scrollTop() + $(window).height() >= $(document).height() - 50){
        //code to trigger function goes here
    }
});

因此,当用户滚动到页面底部时,它将加载更多内容。

所以我想让$.each只调用doAjax() 3或4次。 我遇到的问题是它从数组中调用了相同的值,所以我做了一个临时变量并将原始数组存储在其中,如下所示:

var temp = categories; 

然后每次$.each运行时,我都会从temp数组中删除该值。

我知道这不是他做事的最佳方式,而是我能想到的。

如果您可以提出解决此问题的更好方法,将不胜感激。 否则,我希望$ .each在文档加载时至少运行一次(并仅循环3或4个元素),然后删除它已经经历的数组元素,然后在文档重新运行(仅通过3或4个元素)用户滚动到页面底部,直到temp数组中没有其他元素。

要循环并删除类别数组,请尝试,

function sendAjax(cat) {
    if(cat.length>1){
     var len = ( cat.length > 3 )  ? 3 : cat.length;
     for (var i = 0; i < len; i++) { //send ajax 3 times
        if (typeof cat[i] != "undefined") {
           // doAjax(cat[i]);
        }
     }
    }
    cat = cat.splice(len);//remove the first three elements from array
    return cat;  
}

如何追加数组=> doAjax函数的所有结果,然后全部完成,然后追加到您的页面。.ala

这可能有助于减少数组:

var arr2 = categories.splice(0); // copy the original categories array to a new array
var rotationNum = 3;
function sendIt(){
   var lngth = (arr2.length < rotationNum) ? arr2.length : rotationNum; 
   for (var i = 0; i < lngth ; i++){
    //doAjax
   }
   arr2.splice(0,lngth);
}

或尝试在下面存储所有ajax调用,然后追加。

var categoriesDeferred = [];

for(var i = 0; i < categories.length; i++){
  categoriesDeferred.push(doAjax(categories[i]));
}

$.when.apply($, categoriesDeferred).then(everythingDoneFunc); 

function doAjax(data) {
  var dferred = $.Deferred();    
  //your ajax call here.. .
  setTimeout(function() { dferred.resolve() }, 2000);    

  return dferred.promise();
}

function everythingDoneFunc(){
  console.log('everything processeed');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM