我有两个输入复选框:
<input type="checkbox" checked='true' />
<input type="checkbox" checked='true' />
尝试使用jQuery来允许两个输入表现相同。如果选中第一个复选框,则选中第二个。如果未选中1st,则不检查2nd。反之亦然。
我的代码:
$('input:checkbox').live('change', function() {
$('input:checkbox').siblings().prop('checked',$(this).is(":checked"));
});
在这里调用.live()而不是.on(),因为我只能使用jQuery 1.6.4
这样可行,但是如果我将这些输入标签变形为两种形式,它将不再起作用。为什么?我该如何解决这个问题?
<form>
<input type="checkbox" checked='true'/>
</form>
<form>
<input type="checkbox" checked='true'/>
</form>
答案 0 :(得分:2)
在使用input
元素包装form
元素后,输入不再是兄弟元素。您可以在父表单上使用.siblings()
,然后将input:checkbox
放在其中:
$('input:checkbox').live('change', function() {
$(this)
.parent()
.siblings('form')
.find('input:checkbox')
.prop('checked', $(this).is(":checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<form>
<input type="checkbox" class="example" checked='true' id="1" />
</form>
<form>
<input type="checkbox" class="example" checked='true' id="2" />
</form>
答案 1 :(得分:0)
当你在DOM中彼此分隔复选框元素并将它们嵌套在不同的元素中时,它们不再是彼此的兄弟姐妹,而且JQuery方法.siblings()不会返回它们。
您可以使用类标记它们,然后按类过滤并相应地设置复选框值,而不是依赖于复选框位置。
$('.example').live('change', function() {
$('.example').prop('checked',$(this).is(":checked"));
});
为您制作了一个小型JFiddle样本 - https://jsfiddle.net/sa4eu86d/3/
答案 2 :(得分:0)
删除jQuery中的兄弟姐妹。所以它应该是:
$('input:checkbox').prop('checked',$(this).is(":checked"));
这将解决您的问题。