您好我只想尝试在淘汰赛中与结算复选框一样简单。这是我的例子:
http://jsfiddle.net/neosketo/kmwpop19/1/
我的javascript可以在jquery中工作,但我不想使用jquery:
var MainViewModel = function () {
var self = this;
self.States = ko.observableArray([{Value:"CA",Name:"California"},
{Value:"FL",Name:"Florida"},
{Value:"NY",Name:"New York"},
{Value:"VG",Name:"Virginia"},
{Value:"TX",Name:"Texas"}
]);
self.SelectedState = ko.observable();
self.SelectedShippingState = ko.observable();
self.myValue = ko.observable(false);
self.myAction = function() {
if (self.myValue) {
this.SelectedShippingState().Value = this.SelectedState().Value;
} else {
self.SelectedShippingState().Value = null;
}
return true;
};
}
ko.applyBindings(new MainViewModel());
答案 0 :(得分:1)
不要同时使用checked
和click
绑定。
<input type="checkbox" data-bind="checked: myValue, click: myAction" /> Same as Billing<br/>
将复选框绑定到变量后,订阅它以处理更改:
self.myValue.subscribe(function(newValue) {
if (newValue) {
self.SelectedShippingState(self.SelectedState());
} else {
self.SelectedShippingState(null);
}
});
您的代码存在许多其他问题,包括用于绑定的内容以及Value
在哪里发挥作用。在此更正:
var MainViewModel = function() {
var self = this;
self.States = ko.observableArray([{
Value: "CA",
Name: "California"
}, {
Value: "FL",
Name: "Florida"
}, {
Value: "NY",
Name: "New York"
}, {
Value: "VG",
Name: "Virginia"
}, {
Value: "TX",
Name: "Texas"
}]);
self.SelectedState = ko.observable();
self.SelectedShippingState = ko.observable();
self.myValue = ko.observable(false);
self.myValue.subscribe(function(newValue) {
if (newValue) {
self.SelectedShippingState(self.SelectedState());
} else {
self.SelectedShippingState(null);
}
return true;
});
}
ko.applyBindings(new MainViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Billing State:
<select data-bind="options: States, optionsText: 'Name', optionsValue: 'Value', value: SelectedState, optionsCaption: 'Choose a Billing State'"></select>
<hr/>
<input type="checkbox" data-bind="checked: myValue" />Same as Billing
<br/>Shipping State:
<select data-bind="options: States, optionsText: 'Name', optionsValue: 'Value', value: SelectedShippingState, optionsCaption: 'Choose a Shipping State'"></select>
<br>
请注意,如果您选中该框然后更改第一个下拉菜单,则它们不会保持同步。这将要求第二个是计算的。