Dre*_*ild 0 html binding knockout.js
我有两个复选框,我希望这些复选框的值相互依赖.当我检查第一个复选框时,第二个是取消选中,当我取消选中第一个时,第二个被检查,反之亦然.我可以用jQuery做这个:例子.
$('input').on('change',
function() {
var anotherId = $(this).attr('id') == 'first' ? 'second' : 'first';
if($(this).is(':checked'))
$('[id="' + anotherId + '"]').removeAttr('checked');
else
$('[id="' + anotherId + '"]').attr('checked', 'true');
});
Run Code Online (Sandbox Code Playgroud)
但这不是我想的最好的方式.我知道我可以用knockout.js来做,但不知道怎么做.你能帮我解决这个问题吗?
您是否考虑使用单选按钮?;-)
你没有给出太多实际背景; 有很多方法可以解决这个问题,最好的方法取决于具体情况.无论如何,这是一种方法.
为值创建"私有"可观察对象,并且具有"公共"计算的可观察对象,这些可观察对象在该write
位内部具有一些额外的逻辑(类似于C#中具有复杂setter的属性):
var ViewModel = function() {
var self = this;
var _first = ko.observable(true);
var _second = ko.observable(false);
self.first = ko.computed({
read: _first,
write: function(val) {
_first(val);
_second(!val);
}});
self.second = ko.computed({
read: _second,
write: function(val) {
_second(val);
_first(!val);
}});
};
ko.applyBindings(new ViewModel());
Run Code Online (Sandbox Code Playgroud)
看看这个小提琴的工作演示.再次注意,复选框现在只是表现得像是单选按钮......