[英]Call a function inside jquery each
我有一個jQuery的每個函數。在其中我正在調用一個函數。每個函數中的函數只有在上一個元素完成此函數時才應調用。
function x(t){
var a = something;
$.each(a, function(index,value){
y(this);
});
}
function y(t){
$.ajax({
}).done(function(r){
if(r.success){
}
else{
}
});
// This function should be called for the second element
// in the each function only if its completed for the first element.
}
$.each
是同步函數,因此下一次迭代僅在當前函數完成時發生(包括調用和執行y(this)
,除非內部有異步動作)
要使用Ajax來做到這一點:
使用遞歸模擬循環。
var currentIndex = 0;
function x(t) {
if (currentIndex >= something.length) {
return;
}
$.ajax({
url: '',
data: something[currentIndex],
success: function () {
currentIndex++;
x(t);
}
});
}
如上文所述,該函數是同步運行的,因此,當第2項到達時,它已經由第1項完成了。
這是示例,但實際上是y函數運行異步的事實,但您未指定否?
function x(t){ var a = ["one", "two", "tree"]; $.each(a, function(index,value){ y(this, index); }); } function y(t, index){ // This function should be called for the second element // in the each function only if its completed for the first element. console.log(index + " "+ t +" => running in y") } x("")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.