2009-09-24 74 views
0

我有這個問題,我在這個選擇組上做了一個.each(),對於每一個它觸發一個調用服務器的一些數據來填充它。然而,我不明白爲什麼它只會填充最底層。然後我扔了一些警報(),並意識到它只是多次運行最後一個回調函數。我意識到,到第一次JSON調用完成時,$(this)是不同的......我怎麼才能讓它等待,所有這些都會被正確的調用填充?

這裏是SCRIPT部分:

var thisbundle; 
    var testcount = 0; 

    //get bundle options first.. 
    $("select.bundle").each(function(){ 

      thisbundle = $(this); 
     testcount++; 
      var url = "/order/getpricing/" + thisbundle.attr("id"); 

     //clear it out... 
      //thisbundle.children().remove(); 

     var passbundle = thisbundle; 
      $.getJSON(url, function(data, passbundle){ 
       var options = ''; 
       for(n = 0; n < data.length; n++){ 
        options += '<option value="' + data[n].volumeID + '">' + explainPricing(data, n) + '</option>'; 

        } 
       passbundle.html(options); 
     }); 
    }); 

這裏是組成部分:

<div id="bundles"> 
<table> 
    <%foreach (KODmvc.Models.Product prod in Model.products) 
     {%> 
      <%if (prod.NumberOfCourses > 1) 
       { %> 
       <tr><td><img src="<%=prod.Icon %>" /></td><td><b><%=prod.Title%></b><br /><%=prod.Description%></td><td><select class="bundle" id="<%=prod.ProductID %>"><option value="-1">None</option>"</select></td></tr> 
      <%} %> 
    <%} %> 
    </table> 
</div> 
+1

您需要顯示一些代碼才能回答。但是,一般情況下,通過捕獲本地變量中想要的值來解決這類問題。 –

+0

現在看代碼:) – BigOmega

回答

2

申報thisbundle在你的功能,而不是在全球範圍內:

$("select.bundle").each(function(){ 
    var thisbundle = $(this); 
    // … 
}); 

否則全局對象將在每次迭代回調函數會再使用被覆蓋。

+0

是不是有其他方法? – BigOmega

+0

更改了我的答案。 – Gumbo

+0

謝謝,這工作,有趣我之前嘗試過,我認爲它沒有工作,但我認爲這是因爲我發現我引用了一個屬性錯誤的方式,所以我認爲$(this)不是$(this )我以爲這是... – BigOmega

3

括在這樣一個匿名函數Ajax調用。這會爲每個選擇元素創建一個新的閉包。每個關閉都會記住它自己的值爲passbundle

$("select.bundle").each(function(){ 
    thisbundle = $(this); 
    testcount++; 
    var url = "/order/getpricing/" + thisbundle.val(); 
    alert(thisbundle.id); 

    //clear it out... 
    //thisbundle.children().remove(); 

    (function(){ 
     var passbundle = thisbundle; 
     $.getJSON(url, function(data, passbundle){ 
      var options = ''; 
      for(n = 0; n < data.length; n++){ 
       options += '<option value="' + data[n].volumeID + '">' + explainPricing(data, n) + '</option>'; 
      } 
      passbundle.html(options); 
     }); 
    })(); 

}); 
+0

如果我停止使用passbundle,我仍然可以使用此捆綁包嗎? – BigOmega

+1

它不會工作。每次運行外循環時,您都會看到此捆綁器的值發生更改。由於範圍的原因,你的內部函數帶有一個'實時'指向這個變量的指針。當你的事件處理程序運行時,'thisbundle'變量的值將是它的最後一個值。 –

+0

但我注意到passbundle沒有正常工作,說它沒有.html,我認爲這是因爲$(this)在內部變成了一個JSON調用? – BigOmega

1

你也可以使用async:false,雖然如果你正在循環,那可能是錯誤的方向。但值得一看。