gpt4 book ai didi

javascript - 使用 jQuery 检查父复选框

转载 作者:行者123 更新时间:2023-11-30 13:41:23 25 4
gpt4 key购买 nike

基本上,我正在尝试编写一个 js 函数,如果我选中子复选框,则父复选框也会选中(如果尚未选中)。我在这里使用 jquery 是我的 html:

      <ul id="ulParent" style="margin: 0; padding: 0; list-style: none;">
<li style="margin: 0 0 5px 0;">
<input type="checkbox" checked="checked" class="liParent" id="p1" />Parent1
<ul id="ulParent" style="margin: 0; padding: 0; list-style: none;">
<li>
<input type="checkbox" checked="checked" class="liChild" id="c1" onclick="checkParent(this);" />Child1
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c2" onclick="checkParent(this);"/>Child2
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c3" onclick="checkParent(this);"/>Child3
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c4" onclick="checkParent(this);"/>Child4
</li>
</ul>
</li>

<li style="margin: 0 0 5px 0;">
<input type="checkbox" checked="checked" class="liParent" id="p2" />Parent2
<ul id="ulParent" style="margin: 0; padding: 0; list-style: none;">
<li>
<input type="checkbox" checked="checked" class="liChild" id="c1" onclick="checkParent(this);" />Child1
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c2" onclick="checkParent(this);"/>Child2
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c3" onclick="checkParent(this);"/>Child3
</li>
<li>
<input type="checkbox" checked="checked" class="liChild" id="c4" onclick="checkParent(this);"/>Child4
</li>
</ul>
</li>
</ul>

JS 函数

function checkParent(child){

if (child != null) {

// if child is checked we need to check the parent category
if (child.checked) {
// get the parent checkbox and check it if not check....need help here....
$(child).parent().parent().parent()......

}
}
}

最佳答案

我将删除 HTML 中的内联 javascript 并使用 jQuery 绑定(bind)来绑定(bind)检查事件:

$(document).ready(function() {
$('input.liChild').change(function() {
if ($(this).is(':checked')) {
$(this).closest('ul').siblings('input:checkbox').attr('checked', true);
}
});
});

这将自动将您要查找的事件绑定(bind)到类 liChild 的任何输入,而无需所有这些点击。

关于javascript - 使用 jQuery 检查父复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2119220/

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