jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用jQuery在单独的DIV中包装任意内容(H2,H3,P等)大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_673_4@ 希望使用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和后续段落将在第一列.
>接下来的两个H3和后续段落将在第二列.
>其余的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 <p> elements into <div> between <h3>
> need to wrap h3 and div in wrapper div with jquery
> @L_419_4@

但是这些解决方案更具体地适用于从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在单独的DIV中包装任意内容(H2,H3,P等)全部内容,希望文章能够帮你解决使用jQuery在单独的DIV中包装任意内容(H2,H3,P等)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。