我有一个包含 2 个复选框的示例。我想确保始终有 1 个复选框处于事件状态,这意味着复选框 1 或复选框 2 或两者都可以处于事件状态。我该怎么做?
function DemoItem(id, name) {
var self = this;
self.id = ko.observable(id);
self.Name = ko.observable(name);
self.Selected = ko.observable(false);
}
function ViewModel() {
var self = this;
self.availableItems = ko.observableArray();
self.associatedItemIds = ko.observableArray();
self.init = function () {
self.availableItems.push(new DemoItem(1, 'One'));
self.availableItems.push(new DemoItem(2, 'Two'));
};
self.toggleAssociation = function (item) {
if (item.Selected() === true) console.log("dissociate item " + item.id());
else console.log("associate item " + item.id());
item.Selected(!(item.Selected()));
return true;
};
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Available Items:
<div data-bind="foreach: $root.availableItems">
<input type="checkbox" data-bind="value: id(), checked: $root.associatedItemIds, click: $root.toggleAssociation" />
<span data-bind="text: ' ' + Name()"></span>
<br/>
</div>
<br/>
Associated Item Ids:
<div data-bind="foreach: $root.associatedItemIds">
<span data-bind="text: $data"></span>
<br/>
</div>
最佳答案
在 self.toggleAssociation
中,每当您取消选中某些内容时,您首先会通过遍历 self.availableItems
并计算这些来计算选中了多少 item
为此 item.Selected() === true
。如果只有一个,那么您不要取消选中它。
self.toggleAssociation = function (item) {
if (item.Selected() === true) {
var howManyAreSelected = 0;
ko.utils.arrayForEach(self.availableItems(), function (item) {
if (item.Selected() === true) {
howManyAreSelected += 1;
}
});
if (howManyAreSelected > 1) {
item.Selected(false);
}
}
else {
item.Selected(true);
}
return true;
};
关于javascript - 如何创建至少有 1 个框处于事件状态的复选框列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36864900/