单选按钮Knockoutjs [英] Radio buttons Knockoutjs
问题描述
我有两个从服务器A和B获得的值.一次只能有一个真值.
I have 2 values that I get from server A and B. I can only have one true at a time.
我再次需要一次检查一台收音机,所以只有一个真实值.
Again what I need is one of the radios to be checked at a time so one true value only.
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>
推荐答案
checked
绑定对于单选按钮和复选框的工作方式有所不同:
The checked
binding works differently for radio buttons and checkboxes:
来自文档:
对于单选按钮,KO将设置要检查的元素. 如果,则该参数值等于单选按钮节点的
value
属性. 因此,您的参数值应为字符串.
For radio buttons, KO will set the element to be checked if and only if the parameter value equals the radio button node’s
value
attribute. So, your parameter value should be a string.
因此,您需要将输入的value
属性设置为"A"和"B",然后绑定到radioSelectedOptionValue
,根据选择的选项,该radioSelectedOptionValue
将包含"A"或"B":
So you need to set the value
attribute of your inputs to "A" and "B" and then bind to the radioSelectedOptionValue
which will contain "A" or "B" depending on which options is selected:
<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
的值:>
If you want to keep your boolean properties: A
and B
, you need to make them ko.computed
(read-only, writable) which will use/convert the value of the radioSelectedOptionValue
:
this.radioSelectedOptionValue = ko.observable();
this.A = ko.computed( {
read: function() {
return this.radioSelectedOptionValue() == "A";
},
write: function(value) {
if (value)
this.radioSelectedOptionValue("A");
}
}, this);
演示 JSFiddle.
这篇关于单选按钮Knockoutjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!