允许两个输入复选框在jquery中表现相同

allow the two input checkbox behave the same with jquery

本文关键字:jquery 许两个 输入 复选框      更新时间:2023-09-26

我有两个输入框:

<input type="checkbox" checked='true' />
<input type="checkbox" checked='true' />

尝试使用jQuery来允许两个输入行为相同。如果选中第一个复选框,则选中第二个复选框。如果第1项未选中,则第2项未选中。反之亦然。

代码:

$('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>

在用form元素包装input元素后,输入不再是兄弟元素。您可以在父窗体上使用.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>

在jQuery中添加兄弟元素。所以应该是:

  $('input:checkbox').prop('checked',$(this).is(":checked"));

当你在DOM中把复选框元素分开并嵌套到不同的元素中时,它们就不再是兄弟元素了,JQuery方法。siblings()也不会返回它们。

不依赖复选框的位置,你可以使用类标记它们,然后按类过滤,并相应地设置复选框的值。

$('.example').live('change', function() {
  $('.example').prop('checked',$(this).is(":checked"));
});

为您制作了一个小JFiddle示例- https://jsfiddle.net/sa4eu86d/3/