无需添加类,如何用jQuery包裹两个标题间的所有元素?
解决方案
你只需要把原代码里的.next()替换成nextUntil(':header'),再用wrapAll替代wrap就能解决多元素包裹的问题,具体修改后的代码如下:
$(document).ready(function() { $(".axxs-accordion > :header").addClass("h-trigger static") .nextUntil(':header') .wrapAll("<div class='section collapsed'></div>"); });
关键逻辑说明
:header选择器:这是jQuery内置的选择器,直接匹配所有h1到h6的标题元素,完全不需要额外加类。nextUntil(':header'):会选中当前标题之后、下一个任意层级标题(h1-h6)之前的所有同级元素,完美覆盖多元素混合的场景。wrapAll():把选中的所有元素一次性包裹到同一个div容器里,而不是像wrap()那样给每个元素单独套容器,正好匹配你“包裹两个标题间所有元素”的需求。
修改后你的HTML会被处理成预期的结构:
<div class="axxs-accordion"> <h2 class="h-trigger static">Section with a Paragraph</h2> <div class="section collapsed"> <p>Here is some text content</p> </div> <h2 class="h-trigger static">Section with a Div and Mixed Content</h2> <div class="section collapsed"> <h3>Heading</h3> <p>Here is some content with text and a link.</p> <p><a href="#" target="_blank">Test link</a></p> </div> <h2 class="h-trigger static">Section with a List</h2> <div class="section collapsed"> <ul> <li>List item 1</li> <li>List item 2</li> </ul> </div> </div>
内容的提问来源于stack exchange,提问作者DeanH
相关产品推荐
相关产品推荐

