使用jQuery在单独的div中包装任意内容(H2,H3,P等)



希望使用jQuery将任意数量的用户提供的内容包装成有效的三列。初始的HTML看起来像这样:

<div#content>
    <h2>Page Title</h2>
    <p>Some arbitrary number of paragraphs followed by some arbitrary number of biographies, with an arbitrary number of paragraphs.</p>
    <p>Paragraph.</p>
    <h3>First Person</h3>
    <p>Paragraph.</p>
    <p>Paragraph.</p>
    <h3>Second Person</h3>
    <p>Paragraph.</p>
    <h3>Person Three</h3>
    <p>Paragraph.</p>
    <h3>Person Four</h3>
    <p>Paragraph.</p>
    <h3>Person Five</h3>
    <p>Paragraph.</p>
</div>

目标是将内容包装成三列:

  • 第一个H2和随后的段落将在第一列。
  • 接下来的两个H3s和随后的段落将在第二列。
  • 剩余的H3s(在本例中为三个,可能更多)将在第三列。

所以…

<div#content>
    <div.col1>
        <h2>Page Title</h2>
        <p>Paragraph.</p>
        <p>Paragraph.</p>
    </div>
    <div.col2>
        <h3>First Person</h3>
        <p>Paragraph.</p>
        <p>Paragraph.</p>
        <h3>Second Person</h3>
        <p>Paragraph.</p>
    </div>
    <div.col3>
        <h3>Person Three</h3>
        <p>Paragraph.</p>
        <h3>Person Four</h3>
        <p>Paragraph.</p>
        <h3>Person Five</h3>
        <p>Paragraph.</p>
        <!-- etc. -->
    </div>
</div>

我在这里设置了一个CodePen: http://codepen.io/ian-pvd/pen/GKryq

它正在使用以下方法:

jQuery('h2').nextUntil('h3').andSelf().wrapAll('<div class="col1" />'); 
jQuery('h3:nth-of-type(1)').nextUntil('h3:nth-of-type(3)').andSelf().wrapAll('<div class="col2" />');
jQuery('h3:nth-of-type(3)').nextUntil('p:last-of-type').wrapAll('<div class="col3" />');

这一直工作到第三列,我在包装第三列中剩下的任何内容时遇到了麻烦。

我检查了这些问题,它们提供了一些帮助:

  • Wrap Multiple

    元素放入

    之间& lt; h3>
  • 需要在包装器div中包装h3和div

但是解决方案更具体地从H2到H2包装,而不是在H2和H3标签之间切换,或者在一个集合中包含两个H3标签。

试图说服用户以不同/单独的方式输入内容已经被我排除了。

是否有简单的方法来做到这一点?

谢谢你的帮助!

最后一个选择器h3:nth-of-type(3)没有按照预期匹配,因为您已经包装了第一个和第二个h3;h3原来是第三,现在是第一。

试着用相反的顺序来包装这些列:

jQuery('#content>h3:nth-of-type(3)').nextUntil('div').andSelf().wrapAll('<div class="col3" />');
jQuery('#content>h3:nth-of-type(1)').nextUntil('div').andSelf().wrapAll('<div class="col2" />');
jQuery('#content>h2').nextUntil('div').andSelf().wrapAll('<div class="col1" />'); 

我想我得到了你正在寻找的答案,只是将最后一个选择器调整为:

jQuery('h3:eq(2)').nextUntil('p:last').andSelf().wrapAll('<div class="col3" />');

见http://codepen.io/ian-pvd/pen/GKryq