[英]Deleting dynamically created rows in Knockout.js
我正在使用淘汰表2.3.0,并且我有一个表,其中包含动态添加的行,并在每个行中选择列表。 更改日期输入后,选择列表将填充不同的内容。 因为不同的日期将用不同的内容填充列表,所以我想删除任何以前添加的行,因为内容可能不准确。
我遇到的问题是并非所有行都被删除了。 例如:如果我有4行以上,那么总会剩下2行。 清除所有行的唯一时间是只有一开始时。
这是删除行的订阅函数
self.date.subscribe(function() {
//I also tried setting the loop length to a very long number but the same results happened each time
for (i = 0; i < self.customers().length; i++){
self.customers.remove(self.customers()[i]);
}
//now populate the select list and add an empty row - commented out for testing to make sure rows are being deleted
//setCustomerList(self.date());
//self.customers.push(new AddCustomer(self.customerList[0]));
});
我只是进行测试以查看会发生什么,所以删除所有行的唯一方法是添加多个for循环,这显然是不可取的。
有没有更简单的方法来删除所有动态添加的行?
如果要删除可观察数组中的所有项目,请使用removeAll
方法:
self.customers.removeAll();
如果您确实想使用循环,则可以通过连续移除最后一个(或第一个)项直到没有剩余项来执行此操作:
while (self.customers().length) {
self.customers.pop();
}
我认为您需要反转for循环并从下往上删除项目。 您的代码的问题在于,每次删除项目时,数组的长度都会更改。
self.date.subscribe(function() {
var customerLength = self.customers().length
for (i = customerLength ; i >= 0; i = i - 1){
self.customers.remove(self.customers()[i]);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.