gpt4 book ai didi

javascript - 使用 knockout 选择所有复选框

转载 作者:行者123 更新时间:2023-11-30 17:18:26 24 4
gpt4 key购买 nike

我正在尝试使用 knockout 来选择所有复选框。这是我的 View 模型

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 .你能告诉我我做错了什么吗?

最佳答案

您需要使 person 中的 sel 属性可观察:

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 .

关于javascript - 使用 knockout 选择所有复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25640383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com