[英]Looping through table rows, fetching a total and updating row
I know what the problem is, but I am unsure how to fix it. 我知道问题出在哪里,但是我不确定如何解决。
It is looping through each tr, and then posting to a url to retrieve a total, by the time the post returns a value, the loop has reached the last tr in the table. 它循环遍历每个tr,然后发布到url以检索总计,等到发布返回值时,循环已到达表中的最后一个tr。
So when the .done callback takes place, $tr is referencing the last row in the table. 因此,发生.done回调时,$ tr引用表的最后一行。
What is the best approach to reference the original $tr that the post call was made for? 引用进行邮递的原始$ tr的最佳方法是什么?
$div.find('table tbody tr').each(function() {
$tr = $(this);
associationId = $tr.data('id');
$.post(settings.UrlFetch, {competition_id: settings.CompetitionId, association_id: associationId})
.done(function (res) {
if (res.success) {
$tr.find('.total').html('$' + Number(res.data.total).toFixed(2));
} else {
alert(res.errors);
}
})
.fail(function (res) {
alert("Unknown Error Occurred");
});
});
The problem is you are using a global variable $tr
which is overriden in each iteration of the each
callback, you need to use a closure variable(by declaring $tr
using var
) to have a local instance of $tr
in each call of the callback 问题是您使用的是全局变量$tr
,该变量在each
回调的每次迭代中都被覆盖,您需要使用闭包变量(通过使用var
声明$tr
)在$tr
的每次调用中都具有$tr
的本地实例打回来
$div.find('table tbody tr').each(function () {
var $tr = $(this); //use local variable
associationId = $tr.data('id');
$.post(settings.UrlFetch, {
competition_id: settings.CompetitionId,
association_id: associationId
}).done(function (res) {
if (res.success) {
$tr.find('.total').html('$' + Number(res.data.total).toFixed(2));
} else {
alert(res.errors);
}
}).fail(function (res) {
alert("Unknown Error Occurred");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.