4

jQueryを使用して、ユーザーが指定した任意の量のコンテンツを効果的に3つの列にラップすることを検討しています。最初の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>

目標は、コンテンツを3つの列にラップすることです。

  • 最初のH2以降の段落は1列目にあります。
  • 次の2つのH3とそれに続く段落は、2列目にあります。
  • 残りのH3(この場合は3つ、それ以上になる可能性があります)は列3にあります。

それで...

<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" />');

これは3番目の列まで機能しますが、3番目の列に残っているコンテンツをラップするのに問題があります。

私はこれらの他の質問をチェックしました、それはいくつかの助けを提供しました:

ただし、ソリューションは、H2からH2へのラッピングに固有のものであり、H2タグとH3タグを切り替えたり、1つのセットに2つのH3タグを含めたりすることはありません。

別の方法で/別々にコンテンツを入力するようにユーザーを説得しようとすることは、私にとってすでに除外されています。

これを行う簡単な方法はありますか?

ご協力いただきありがとうございます!

4

2 に答える 2

2

私はあなたが探していた答えを得たと思います、ちょうど最後のセレクターを微調整しました:

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

http://codepen.io/ian-pvd/pen/GKryqを参照してください

于 2013-01-17T22:35:10.687 に答える
2

h3:nth-of-type(3)1 番目と 2 番目の h3 を既にラップしているため、最後のセレクターは期待どおりに一致しません。以前は 3 番目だった 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" />'); 
于 2013-01-17T22:27:46.433 に答える