简体   繁体   English

为什么我的Knockout Radio按钮在使用单击绑定的另一个元素内失败?

[英]Why are my Knockout Radio buttons failing when inside another element with a click binding?

I have a list of radio buttons. 我有一个单选按钮列表。 I want clicks on the <li> their in to also check the radio button. 我想点击<li>他们的内容也检查单选按钮。 This all works up until I put a name attribute on the radio elements. 这一切都有效,直到我在无线电元素上添加了name属性。 Then my code stops working. 然后我的代码停止工作。

Here is what my code looks like: 这是我的代码的样子:

<ul data-bind="foreach: rows">
    <li data-bind="click: function() { $parent.val($data); }">
        <input type="radio" name="my_radio" data-bind="value: $data, checked: $parent.val" />
        <label data-bind="text: $data"></label>
    </li>
</ul>

Here are two test cases. 这是两个测试用例。

Be sure to click on both the radio button and row. 务必单击单选按钮和行。

Working: http://jsfiddle.net/Dihedral/HJGxX/2/ 工作: http //jsfiddle.net/Dihedral/HJGxX/2/

Not Working: http://jsfiddle.net/Dihedral/HJGxX/3/ 不工作: http //jsfiddle.net/Dihedral/HJGxX/3/

In the second case and when clicking on just the radio, you'll see that the val() observable is being updated, but the UI is not. 在第二种情况下,当只是单击收音机时,您将看到val()observable正在更新,但UI不是。 Anyone know what's going on here, or can see a workaround? 任何人都知道这里发生了什么,或者可以看到解决方法?

The click is not reaching the radio button because knockoutjs returns false from the click handler, preventing the default action to happen (see: note 3 ). 单击未到达单选按钮,因为knockoutjs从单击处理程序返回false,从而阻止默认操作发生(请参阅: 注释3 )。 Just return true from the click handler ( http://jsfiddle.net/HJGxX/4/ ): 只需从点击处理程序( http://jsfiddle.net/HJGxX/4/ )返回true:

<li data-bind="click: function() { $parent.val($data); return true; }">

Having the name attributes all set to the same value makes all these radio buttons part of the same set, and you can only select one of them at once. 将name属性设置为相同的值会使所有这些单选按钮成为同一组的一部分,并且您只能一次选择其中一个。

Read more about on radio buttons name attribute on www.W3.org www.W3.org上阅读有关单选按钮名称属性的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM