我从服务器A和B获得了2个值。我一次只能有一个值。
我需要的是一次要检查的无线电之一,只有一个真正的值。
var viewModel = {
radioSelectedOptionValue: ko.observable("false"),
A: ko.observable("false"),
B: ko.observable("false")
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.1.0/knockout-min.js"></script>
<div class='liveExample'>
<h3>Radio View model</h3>
<table>
<tr>
<td class="label">Radio buttons:</td>
<td>
<label><input name="Test" type="radio" value="True" data-bind="checked: A" />Alpha</label>
<label><input name="Test" type="radio" value="True" data-bind="checked: B" />Beta</label>
</td>
</tr>
</table>
A-<span data-bind="text: A"></span>
B-<span data-bind="text: B"></span>
</div>
答案 0 :(得分:29)
checked
绑定对单选按钮和复选框的工作方式不同:
对于单选按钮,KO将设置要检查的元素当前 if 参数值等于单选按钮节点的
value
属性。 因此,您的参数值应为字符串。
因此,您需要将输入的value
属性设置为“A”和“B”,然后绑定到包含“A”或“B”的radioSelectedOptionValue
,具体取决于哪些选项被选中:
<label>
<input name="Test" type="radio" value="A"
data-bind="checked: radioSelectedOptionValue" />
Alpha
</label>
<label>
<input name="Test" type="radio" value="B"
data-bind="checked: radioSelectedOptionValue" />
Beta
</label>
如果你想保留你的布尔属性:A
和B
,你需要使它们ko.computed
(只读,可写),它将使用/转换值radioSelectedOptionValue
:
this.radioSelectedOptionValue = ko.observable();
this.A = ko.computed( {
read: function() {
return this.radioSelectedOptionValue() == "A";
},
write: function(value) {
if (value)
this.radioSelectedOptionValue("A");
}
}, this);
答案 1 :(得分:20)
Knockout 3.x添加了checkedValue绑定选项。这允许您指定字符串以外的值。
<input name="Test" type="radio" data-bind="checked: radioSelectedOptionValue, checkedValue: true" />
<input name="Test" type="radio" data-bind="checked: radioSelectedOptionValue, checkedValue: false" />