jQuery切换类名异常:手风琴组件无法再次点击标题折叠
手风琴组件无法折叠的修复方案
问题原因
你给.h-trigger.static和.h-trigger.active分别绑定了点击事件,但jQuery的静态事件绑定只会在DOM初始化时给匹配的元素绑定事件。初始状态下所有标题都是.static类,只有这些元素绑定了展开事件;当标题切换为.active类后,这个元素并没有绑定对应的折叠事件(因为绑定折叠事件时没有匹配到任何.active元素),所以点击已展开的标题无法触发折叠逻辑。
修复代码
把两个独立的点击事件合并成一个,直接绑定在.h-trigger上,通过判断当前元素的类来执行对应的展开/折叠操作:
<script type="text/javascript"> $(document).ready(function(){ $(".haccordion > :header").addClass("h-trigger static").next().addClass("section collapsed").attr("inert",""); document.querySelectorAll('.h-trigger').forEach(el => { el.setAttribute("tabindex", "0"); el.addEventListener("keydown", e => { if ([" ", "Enter", "ArrowDown"].includes(e.key)) { e.target.click(); } }); }); // 合并成一个点击事件,处理展开/折叠逻辑 $(".h-trigger").click(function(){ const $accordion = $(this).closest(".haccordion"); const isActive = $(this).hasClass("active"); if (isActive) { // 当前是激活状态,执行折叠 $(this).removeClass("active").addClass("static"); $(this).next(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert",""); } else { // 当前是未激活状态,执行展开(同时关闭其他) $accordion.find(".h-trigger.active").removeClass("active").addClass("static"); $accordion.find(".section.expanded").removeClass("expanded").addClass("collapsed").attr("inert",""); $(this).removeClass("static").addClass("active"); $(this).next(".section.collapsed").removeClass("collapsed").addClass("expanded").removeAttr("inert",""); } }); }); </script> <div class="haccordion"> <h2>Section with a paragraph</h2> <p>Here is some text content</p> <h2>Section with a div</h2> <div> <h3>Heading</h3> <p>Here is some content with text and an image</p> <p><a href="#">Test link</a></p> </div> <h2>Section with a list</h2> <ul> <li>List item 1</li> <li>List item 2</li> </ul> </div>
关键修改说明
- 移除了原来两个分开的
.static和.active点击事件,统一绑定到.h-trigger上,确保所有标题元素都能触发事件,不管类名后续怎么变化。 - 通过
hasClass("active")判断当前标题的状态,分别执行折叠或展开逻辑:- 如果是激活状态(已展开),就切换回静态类,折叠对应内容。
- 如果是静态状态(未展开),先关闭手风琴里其他已展开的内容,再展开当前内容。
内容的提问来源于stack exchange,提问作者DeanH
相关产品推荐
相关产品推荐

