jQuery实现CheckboxTree点击复选框自动折叠问题求助
问题根因
- 事件冒泡:点击复选框/对应label时,点击事件会向上冒泡到父级
<li>元素,触发了绑定在li上的展开/折叠切换逻辑,导致节点自动折叠。 - 事件绑定缺陷:原有代码仅给带有
.open类的li绑定了点击事件,当li切换为.closed类后,原有绑定事件会失效,无法再次点击切换状态。 - 拼写错误:代码中判断半选状态时将
length错写为lenght,会导致半选状态逻辑异常。
修复方案
1. JavaScript代码修改
$(document).ready(function () { // 复选框联动逻辑 $('input[type="checkbox"]').change(function (e) { // 阻止事件冒泡,避免触发父级li的折叠逻辑 e.stopPropagation(); var checked = $(this).prop("checked"), container = $(this).parent(), siblings = container.siblings(); container.find('input[type="checkbox"]').prop({ indeterminate: false, checked: checked }); function checkSiblings(el) { var parent = el.parent().parent(), all = true; el.siblings().each(function () { return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked); }); if (all && checked) { parent.children('input[type="checkbox"]').prop({ indeterminate: false, checked: checked }); checkSiblings(parent); } else if (all && !checked) { parent.children('input[type="checkbox"]').prop("checked", checked); // 修复拼写错误:lenght改为length parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0)); checkSiblings(parent); } else { el.parents("li").children('input[type="checkbox"]').prop({ indeterminate: true, checked: false }); } } checkSiblings(container); }); // 阻止label点击事件冒泡 $('label').click(function(e) { e.stopPropagation(); }); // 用事件委托绑定展开折叠逻辑,适配所有li的状态切换 $("#tree").on("click", "li.open, li.closed", function (e) { // 仅当点击的是li本身(即加减号区域)时触发切换 if (e.target === this) { $(this).toggleClass("open closed"); } }); });
2. CSS代码调整(可选,优化交互体验)
将点击指针样式仅限定给加减号区域,避免复选框和label也显示可点击的指针:
#tree { width: auto; height: 350px; line-height: 20px; border: 1px solid #ccc; padding: 10px; margin: 10px; overflow: scroll; overflow-x: hidden; } #tree .open > ul { display: none; } #tree .open::before, #tree .closed::before { cursor: pointer; font-size: 25px; display: inline-block; margin-left: 2px; width: 20px; } #tree .open::before { content: "\002B"; } #tree .closed::before { content: "\2212"; }
HTML代码无需修改,使用原有代码即可。修改后即可实现仅点击加减号触发展开折叠,点击复选框/标签仅触发勾选逻辑、节点保持展开状态的效果,同时修复了半选状态异常、切换类后事件失效的问题。
内容的提问来源于stack exchange,提问作者Lesika
相关产品推荐
相关产品推荐

