如果所有值都为真,则淘汰 JS 单选按钮选择最后一个按钮

Knockout JS Radio buttons selecting last button if all values are true

我想做的是显示一些带有来自服务器的数据的单选按钮。问题是单选按钮的选中值可能全部为假,然后 KO 自动选择最后一个单选按钮,就像我在下面创建的 JS fiddle 中一样。如果其中一个值是真的,这将完全按预期工作,但在我的情况下,这些值很可能都是假的。

https://jsfiddle.net/9mtzbmng/1/

 self.addItems = function (items) {
            for (var x in items)
            {
                self.Items.push(new Item(items[x]));
            }
        }
    function Item(items) {
     this.ID = items.ID;
     this.Checked = ko.observable(false);
    }

 <input type="radio" data-bind="value: $data.ID,checked: Checked, checkedValue: Checked" name="items">

编辑: https://jsfiddle.net/hrhuym0u/ 通过设置 checkedValue: 'true' 和设置 this.Checked = ko.observable("false")!

遵循此 jsfiddle 后,我的问题得到解决

来自documentation:

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 or the value specified by the checkedValue parameter

在您的情况下,您需要将 checkedValue 设置为 true,因此当您的 Checked observable 包含 true 时,它才会检查您的单选按钮:

<input type="radio" name="radioB" data-bind="value: $data.ID, 
                                             checked: Checked, 
                                             checkedValue: true">

演示 https://jsfiddle.net/r6njzje3/

注意:如果您的单选按钮具有相同的 name,那么它们将组成一组,因此只能选中其中一个,也就是说,在您的原始示例中,总是选中最后一个。因为 checked 总是等于 checkedValue 的值。因此,如果您删除名称 name="radioB",您的所有收音机都会被检查。

注意 2:您应确保 Checked 属性中有实际的 boolean 值,并且您的服务器不会将它们作为字符串发送,例如"true",因为在这种情况下您还需要将 checkedValue 指定为字符串:

<input type="radio" name="radioB" data-bind="value: $data.ID, 
                                             checked: Checked, 
                                             checkedValue: 'true'">

演示:https://jsfiddle.net/hrhuym0u/