2011-09-01 70 views
1

我正在一個頁面上,其中我有2個嵌套循環,我的問題是...說例如外循環的當前值是1,並應執行1次。內循環應執行2次。現在當我警告內循環外循環的值,它會引發我2,第一次嘗試..我不明白它是如何得到2,因爲我的初始值是1,條件是< = 1。當我嘗試打印內循環的值時,它會在第一次和第二次返回1 ...這是瘋狂的行爲...我完全卡在這裏...下面是我的代碼。迭代在jQuery中的嵌套循環asp.net

for (i = 1; i <= _leftSectionCount; i++) //_leftSectionCount is 1{ 
        $("#tdSection" + i + "Image").html("<img width='500' height='35' src='/newsletterimage/section" + i + ".gif'>"); 
        var rows = $("#divLeft" + i + "tbody1 td:nth-child(1)"); // has 2 rows 
        if (rows.length > 0) { 
         $("#tdSection" + i + "Data").append("<table id='tblSection" + i + "Data'></table>"); 
         $("#tblSection" + i + "Data").html(""); 
        } 
        rows.each(function (index) { 
         $.ajax({ 
          type: "POST", 
          url: "AjaxMethods.aspx/GetArticleDetails", 
          data: "{'articleId':'" + $(this).text() + "'}", 
          dataType: "json", 
          contentType: "application/json", 
          success: function (data) { 
           var results = data.d; 
           alert("$(#tblSection" + i + "Data')"); // this returns me 2. 
           alert("$(#tblSection" + index + "Data')"); // this returns me 1 and 0. 
           $("#tblSection" + i + "Data").append("<tr><td>" + results[0].Title + "</td></tr>"); 
          }, 
          error: function (data) { alert(data.responseText); } 
         }); 
        }) 

        WriteToFile(); 
       } 

任何人請幫助我我完全卡在這裏。

回答

1

您的回答也回來了異步,所以i會不管它是什麼,當它返回時,更改爲async=false保持同步iindex(沒有雙關語):

rows.each(function (index) { 
    $.ajax({ 
    type: "POST", 
    url: "AjaxMethods.aspx/GetArticleDetails", 
    data: "{'articleId':'" + $(this).text() + "'}", 
    dataType: "json", 
    async: false, //HERE 
    contentType: "application/json", 
    success: function (data) { 
     var results = data.d; 
     alert("$(#tblSection" + i + "Data')"); // this returns me 2. 
     alert("$(#tblSection" + index + "Data')"); // this returns me 1 and 0. 
     $("#tblSection" + i + "Data").append("<tr><td>" + results[0].Title + "</td></tr>"); 
    }, 
    error: function (data) { alert(data.responseText); } 
    }); 
}) 
+0

真棒缺口。非常感謝你......幫助了我,我從最後3個小時被困在這裏......從來沒有想過這個......你能幫我一個忙嗎,你能告訴我什麼是異步的使用,當我們必須使用它。願上帝保佑你 – Abbas