我正在尝试使用knockout选择所有复选框。这是我的viewmodel
function MasterViewModel() {
var self = this;
self.People = ko.observableArray([new Person("Test1", false), new Person("Test2", false)]);
self.selectedAllBox = ko.observable(false);
self.selectedAllBox.subscribe(function (newValue) {
if (newValue == true) {
ko.utils.arrayForEach(self.People(), function (item) {
item.sel = true;
});
} else {
ko.utils.arrayForEach(self.People(), function (item) {
item.sel = false;
});
}
});
}
Person = function (name, sel) {
this.Name = name;
this.sel = sel;
}
ko.applyBindings(new MasterViewModel());
这是我的观点
<table>
<thead>
<tr>
<th>Name</th>
<th>
<input type="checkbox" data-bind="checked: selectedAllBox" />
</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: sel" />
</td>
</tr>
</tbody></table>
我无法检查所有内容。这是我的Fiddle。你能告诉我我做错了吗?
答案 0 :(得分:2)
您需要在sel
:
Person
属性
Person = function (name, sel) {
this.Name = name;
this.sel = ko.observable(sel);
}
你需要在selectedAllBox.subscribe
:
self.selectedAllBox.subscribe(function (newValue) {
if (newValue == true) {
ko.utils.arrayForEach(self.People(), function (item) {
item.sel(true);
});
} else {
ko.utils.arrayForEach(self.People(), function (item) {
item.sel(false);
});
}
});
演示JSFiddle。