【问题标题】:How to loop an array with jquery in sequence如何用jquery按顺序循环数组
【发布时间】:2014-09-29 09:59:19
【问题描述】:

我一直在寻找、尝试,但现在我的头撞到了墙上!听起来很简单,但无法超越它!尝试了 .each、.map、deferred、promise 和其他一些,但没有任何效果。

所以我想我可以在这里问: 对于数组中的每个元素,我需要调用一个函数,等待它完成,移动到下一个元素并再次调用相同的函数。

function del(value) {
  //do some stuff taking random time
  console.log(value);
}

function asd() {
  var arr = ["one", "two", "three", "four"];
  $.each(arr, function(key, value) {
    del(value);
  });
}

$(function() {
  $("a").click(function() {
    asd();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#">test</a>

我想确保按正确的顺序获得“一”、“二”、“三”、“四”。目前我有时会得到“三”、“一”、“二”、“四”!

提前致谢, 问候

【问题讨论】:

  • 如果arr 中的值顺序正确,您将始终得到正确的顺序
  • 似乎工作正常...
  • 我认为问题是如何等待del() 完成,然后再进行下一次迭代
  • 是的@Pete,我可能还不够清楚......我需要等待每个 del() 调用完成,然后再调用它
  • @Gotrekk 您将不得不重新调整调用 del 的方式,以便仅在函数完成后调用它 - see this question 它可能会让您知道如何做

标签: jquery arrays loops sequential


【解决方案1】:

我认为这不是数组的循环或顺序,而是 //do some stuff taking random time 我假设它是一个异步调用,很可能是一个 ajax 调用。我用下面的代码处理这种情况;

var arr = ["one", "two", "three", "four"];
function del(arrayParam) {
   var item = arrayParam.shift(); //gets first item and removes it from the array 
   if (item) {
      $(/*your ajax call*/).success(function() { 
              del(arrayParam); /*re call function*/ 
          });
   }
   else {
      // you are don with the array show message/alert etc
   }
}
// and some how call the first call might be a button click etc.
del(arrayParam);

【讨论】:

  • 这感觉是一个很好的解决方案。调整我的代码。会让你知道 :) 谢谢!
【解决方案2】:

我通过在页面加载时调用该函数来使其工作,否则没有事件可以调用该函数。我想这就是你要的,是吗?

(function() {
$("a").click(function() {
    //console.log("test: I'm inside");
    asd();
});
}) ();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 2018-05-18
    • 2023-02-06
    • 1970-01-01
    相关资源
    最近更新 更多