gpt4 book ai didi

javascript - 允许两个输入复选框的行为与 jquery 相同

转载 作者:行者123 更新时间:2023-12-02 14:14:47 27 4
gpt4 key购买 nike

我有两个输入复选框:

<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>

关于javascript - 允许两个输入复选框的行为与 jquery 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39133870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com