单选按钮Knockoutjs

Nov*_*per 22 knockout-2.0 knockout.js

我从服务器A和B获得了2个值.我一次只能有一个值.

我需要的是一次要检查的无线电之一,只有一个真正的价值.

var viewModel = {
    radioSelectedOptionValue: ko.observable("false"),
    A: ko.observable("false"),
    B: ko.observable("false") 
};
ko.applyBindings(viewModel);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 29

checked对于单选按钮和复选框,绑定的工作方式不同:

文档:

对于单选按钮,当且仅当参数值等于单选按钮节点的value属性时,KO才会设置要检查的元素 .因此,您的参数值应该是一个字符串.

因此,您需要将value输入的属性设置为"A"和"B",然后radioSelectedOptionValue根据选择的选项绑定到包含"A"或"B" 的属性:

<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>
Run Code Online (Sandbox Code Playgroud)

如果你想保留你的布尔属性: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);
Run Code Online (Sandbox Code Playgroud)

演示JSFiddle.


小智 24

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" />
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/t73d435v/

  • 当您使用单选按钮作为开关时,这真的非常好。完美的。 (2认同)