2016-10-19 33 views
0

我有一個jQuery的每個函數。在它裏面我調用了一個函數。函數內部的每個函數只有在這個函數完成前一個元素時纔會被調用。調用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. 
} 
+5

爲什麼不會是完整的?它是異步的嗎? – adeneo

回答

5

$.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); 
     } 
    }); 
} 
+0

我在y函數裏面調用了ajax,所以當ajax完成時,它應該檢查。 –

+0

@SandeepKollabathula - 這將是你應該添加到問題中的相關信息。 – adeneo

+0

@adeneo對不起,我將編輯我的代碼,並看到我很清楚從下次 –

0

正如上面說別人,這個功能同步運行,所以,當第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>