我使用动态生成的复选框,类似于以下代码..
<ol data-bind="foreach: items">
<li>
<label>
<input type="checkbox" data-bind="checkedValue: itemValue, checked: $root.itemsChecked" />
<input data-bind="value: itemValue, valueUpdate: 'afterkeydown'" />
</label>
</li>
</ol>
我想添加一个按钮,按下该按钮将选中所有复选框。
真诚感谢所有帮助。
由于
答案 0 :(得分:1)
您可以使用另一个ko.computed
复选框来执行此操作,请参阅示例此方法:
var checkVm = function(data){
this.itemValue = ko.observable(data);
};
var viewModel = function() {
this.items = ko.observableArray([new checkVm("test 1"),new checkVm("test 2")]);
this.selectedItems = ko.observableArray([]);
this.selectAllCheck = ko.computed({
read:function(){
return this.selectedItems().length == this.items().length;
},
write: function(val){
if(val)
this.selectedItems(this.items().map(function(item){return item.itemValue();}))
else
this.selectedItems.removeAll();
},
owner:this
});
}
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<label>
<input type="checkbox" data-bind="checked: selectAllCheck" />
Select all
</label>
<ol data-bind="foreach: items">
<li>
<label>
<input type="checkbox" data-bind="checkedValue: itemValue, checked: $root.selectedItems" />
<input data-bind="textInput: itemValue" />
</label>
</li>
</ol>
<h4> Selected: </h4>
<ol data-bind="foreach: selectedItems">
<li data-bind="text: $data">
</li>
</ol>