我遇到这样的情况:
<!-- First parent -->
<input type="radio" name="parent_1" data-smth="parent_1" />
<!-- Children of this one -->
<input type="radio" name="child" data-parent="parent_1" />
<input type="radio" name="child" data-parent="parent_1" />
<input type="radio" name="child" data-parent="parent_1" />
<!-- Second parent -->
<input type="radio" name="parent_1" data-smth="parent_2" />
<!-- Children of this one -->
<input type="radio" name="child" data-parent="parent_2" />
<input type="radio" name="child" data-parent="parent_2" />
<input type="radio" name="child" data-parent="parent_2" />
<!-- Third parent -->
<input type="radio" name="parent_1" data-smth="parent_3" />
<!-- Children of this one -->
<input type="radio" name="child" data-parent="parent_3" />
<input type="radio" name="child" data-parent="parent_3" />
<input type="radio" name="child" data-parent="parent_3" />
现在我想强制检查到达组。因此,如果有人选择 data-smth="parent_1"
,则其中一个子级 (data-parent="parent_1"
) 也必须被选中。
例如,如果有人点击另一个组的子级,则其父级将被选中。
所以这基本上是双向的。
我曾尝试在 jQuery 中实现类似的功能,但脚本很快就会混淆,然后用户就可以按照自己的意愿进行操作。但一开始,在不尝试混淆逻辑的情况下,它工作得很好。
这是我当前的代码:
$(function() {
$(document).on('click', '[data-smth]', function(){
$('[data-parent="' + $(this).attr('data-smth') + '"]:first').attr('checked', 'checked');
})
$(document).on('click', '[data-parent]', function(){
$('[data-smth="' + $(this).attr('data-parent') + '"]').attr('checked', 'checked');
})
})
如果有想法,我们将不胜感激。
最佳答案
使用 .prop("checked", true);
而不是 .attr('checked', 'checked');
可以正常工作:http://jsfiddle.net/fq1d2sar/
来自jQuery API :
Attributes vs. Properties
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the
.attr()
method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the.prop()
method provides a way to explicitly retrieve property values, while.attr()
retrieves attributes.For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the
.prop()
method. Prior to jQuery 1.6, these properties were retrievable with the.attr()
method, but this was not within the scope ofattr
. These do not have corresponding attributes and are only properties.
关于javascript - 如果选择了父级,则选择子级单选按钮,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26905801/