这与围绕该主题的其他问题类似,但又不同。
我有一个包含记录列表的表,每个记录都有一个选择复选框。
在表标题中,我有一个“全选”复选框。
当用户选中/取消选中“全选”时,将选择/取消选择记录。这工作得很好。
但是,当取消选择一条或多条记录时,我需要取消选择“全选”复选框。
我的标记:
<table>
<thead>
<tr>
<th>Name</th>
<th><input type="checkbox" data-bind="checked: SelectAll" /></th>
</tr>
</thead>
<tbody data-bind="foreach: $data.People">
<tr>
<td data-bind="text: Name"></td>
<td class="center"><input type="checkbox" data-bind="checked: Selected" /></td>
</tr>
</tbody>
</table>
我的脚本(已编辑):
function MasterViewModel() {
var self = this;
self.People = ko.observableArray();
self.SelectAll = ko.observable(false);
self.SelectAll.subscribe(function (newValue) {
ko.utils.arrayForEach(self.People(), function (person) {
person.Selected(newValue);
});
});
}
my.Person = function (name, selected) {
var self = this;
self.Name = name;
self.Selected = ko.observable(false);
}
最佳答案
这有效
self.SelectAll = ko.computed({
read: function() {
var item = ko.utils.arrayFirst(self.People(), function(item) {
return !item.Selected();
});
return item == null;
},
write: function(value) {
ko.utils.arrayForEach(self.People(), function (person) {
person.Selected(value);
});
}
});
但是在选择取消选择全部时会给你一个 ordo n ^ 2 问题,你可以使用一个 pasuable 计算来解决这个问题
http://www.knockmeout.net/2011/04/pausing-notifications-in-knockoutjs.html
编辑:您还可以使用 throttle 扩展计算,这样就可以避免 ordo n^2 问题
.extend({ throttle: 1 })
关于javascript - 当取消选择一项或多项时,knockoutjs 取消选择/选择所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980066/