javascript - 回调完成后从数据表中删除
问题描述
我有一个数据表,每个表上都有一个复选框,还有一个按钮可以触发我对该行的操作。我想在我的操作完成后删除该行。
for (i = 0; i < checkedBoxes.length; i++) {
var chk = checkedBoxes[i];
var tdef = chk.closest("tr").querySelectorAll('td');
var myThing = tdef[1].innerHTML;
service.doSomething(myThing, function (result) {
service.doSomethingElse();
// I would like to remove this row once I'm done with this row
//browseDataTable.row($(chk).parents('tr')).remove().draw();
});
}
我知道我不应该在循环遍历它时删除该行。所以我打算只收集每一行的索引,当一切都完成后,我可以删除它,如下所示:
var myArr = new Array();
for (i = 0; i < checkedBoxes.length; i++) {
service.doSomething(myThing, function (result) {
service.doSomethingElse();
myArr.push(i);
}) // Chrome said 'then' is undefined, so how do I chain callback here?
.then(function () {
// Remove all rows at index in myArr
});
}
该服务不是异步服务,它是一个 ASMX 服务。
解决方案
您正在使用您的服务,就像一个带有回调和Promise 的函数。那么它是哪一个?它需要回调,还是返回 Promise?
看起来它没有返回 Promise,因为您正在尝试链接.then()
并且它是未定义的。
The service isn't async
那你为什么要给它一个回调并尝试链接 a .then()
,如果它是同步的?
无论如何,解决问题的一种简单方法是使用let
,它将为每个循环创建一个范围。
目前 :
for (i = 0; i < checkedBoxes.length; i++) { // i is a global (window) variable, that's bad
service.doSomething(myThing, function (result) {
service.doSomethingElse();
myArr.push(i); // i will always be checkboxes.length
})
}
通过使用 let :
for (let i = 0; i < checkedBoxes.length; i++) { // i is in the local scope
service.doSomething(myThing, function (result) {
service.doSomethingElse();
myArr.push(i); // the value of i will be different (correct) each time
})
}
推荐阅读
- ruby-on-rails - 在现有的 Rails 应用程序中设置 wordpress 博客
- r - R markdown 定义用于格式化的宏
- windows - Easyphp 17.0 未在 Windows Server 2016 上启动
- usb - 如何理解使用 libusb 进行批量传输
- ios - didSet 属性值只出现在 print()
- sql - 查询以获取在 3 列中具有相同值且在 1 列中具有不同值的行
- dart - Dartdoc 找不到任何要记录的库
- r - 如何从模型中提取公式并用于 R 中的另一个模型?
- mongodb - 如何在位置数组上创建 2DSphere 索引?
- java - 在执行 java 代码时,我遇到了错误。请帮我解决这个问题