我遇到了这个问题,我在这组选择上执行 .each() ,对于每个选择,它都会触发对服务器的调用以填充一些数据。然而我不明白为什么它只会填充最底部的一个。然后我加入了一些alerts(),并意识到它只是多次运行最后一个回调函数。我意识到,当第一个 JSON 调用完成时,$(this) 已经有所不同...我怎样才能让它等待,以便所有它们都将由正确的调用填充?
这是脚本部分:
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>
最佳答案
将 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);
});
})();
});
关于javascript - 如何等待$.getJSON()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1474288/