[英]Knockout js checkbox is not checked when setting selected values in the view model
My problem is when I set the values of the selected checkboxes through the viewmodel the checkboxes aren't checked until I click another checkbox.我的问题是,当我通过视图模型设置选定复选框的值时,在单击另一个复选框之前,不会选中复选框。
HTML: HTML:
<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '1', id: '1'}" /> 1
<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '2', id: '2'}" /> 2
<input type="checkbox" data-bind="checked: selectedTags, attr: {value: '3', id: '3'}" /> 3
<button data-bind="click: alertMe">Click Me</button>
JAVASCRIPT:爪哇脚本:
function ViewModel () {
var self = this;
self.selectedTags = ko.observableArray([]);
// I added 1 to the selected tags array
self.selectedTags().push('1');
self.alertMe = function () {
alert(self.selectedTags());
};
}
The correct way of adding items to an observableArray
is to call push
directly on the observableArray
(this way KO will be notified that your array was changed):将项目添加到
observableArray
的正确方法是直接在observableArray
上调用push
(这样 KO 将收到您的数组已更改的通知):
self.selectedTags.push('1'); //no () after selectedTags
In itself it won't solve your problem because you are setting the value
of the checkboxes with the attr
binding, and Knockout (before version 3.0) fires the bindings in order.它本身并不能解决您的问题,因为您正在使用
attr
绑定设置复选框的value
,而 Knockout(3.0 版之前)会按顺序触发绑定。 So your checked
binding gets executed first which does not find the values so it cannot set your checkboxes.所以你的
checked
绑定首先被执行,它没有找到值,所以它不能设置你的复选框。
You can upgrade to knockout 3.0 to solve this or change the order of your bindings:您可以升级到淘汰赛 3.0 来解决此问题或更改绑定顺序:
<input type="checkbox"
data-bind="attr: {value: '1', id: '1'}, checked: selectedTags" /> 1
<input type="checkbox"
data-bind="attr: {value: '2', id: '2'}, checked: selectedTags" /> 2
<input type="checkbox"
data-bind="attr: {value: '3', id: '3'}, checked: selectedTags" /> 3
Just edit HTML:只需编辑 HTML:
<input type="checkbox" data-bind="checked: selectedTags" value="1" id="1" /> 1
<input type="checkbox" data-bind="checked: selectedTags" value="2" id="2" /> 2
<input type="checkbox" data-bind="checked: selectedTags" value="3" id="3" /> 3
<button data-bind="click: alertMe">Click Me</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.