4

こんにちは–私の質問は、意図した出力と実際の出力を要約するのが最善です. 次の HTML と JS コードを使用して、なぜこれを行っているのか手がかりはありますか?

HTML コード:

<h3>CATEGORY 1</h3>
<p>Item 1</p>
<p>Item 2</p>

<h3>CATEGORY 2</h3>
<p>Item 3</p>
<p>Item 4</p>

<h3>CATEGORY 3</h3>
<p>Item 5</p>
<p>Item 6</p>

JavaScript / jQuery コード:

$(".h3").each(function () {

  // Display H3 Text
  console.log($(this).text());

  $(this).siblings('p').each(function () {
    if ( $(this).next().is('h3') ) {

      // Display Last Paragraph Text Before <H3>
      console.log($(this).text());

      // Break the Each Loop, Go to next H3
      return false;
    }
    else {

      // Display Paragraph Text
      console.log($(this).text());
    }
  });
});

意図した出力:

CATEGORY 1
Item 1
Item 2
CATEGORY 2
Item 3
Item 4
CATEGORY 3
Item 5
Item 6

実際の (意図しない) 出力:

CATEGORY 1
Item 1
Item 2
CATEGORY 2
Item 1
Item 2
CATEGORY 3
Item 1
Item 2

ありがとう。

4

4 に答える 4

4

すべての兄弟を選択するためsiblings()、すべての前とすべての後続。私はあなたが必要だと思いますnextAll()

一致した要素のセット内の各要素の後続のすべての兄弟を取得します。オプションでセレクターによってフィルター処理されます。


デモ

$("h3").each(function () {

  // Display H3 Text
  console.log($(this).text());

  $(this).nextAll('p').each(function () {
    if ( $(this).next().is('h3') ) {

      // Display Last Paragraph Text Before <H3>
      console.log($(this).text());

      // Break the Each Loop, Go to next H3
      return false;
    }
    else {

      // Display Paragraph Text
      console.log($(this).text());
    }
  });
});

与える:

CATEGORY 1
Item 1
Item 2

CATEGORY 2
Item 3
Item 4

CATEGORY 3
Item 5
Item 6
于 2010-07-14T18:20:40.130 に答える
2

最後の要素の後に兄弟がいない場合は、代わりに<p>使用すると思います。.nextUntil('h3')

$("h3").each(function() {
  console.log($(this).text());
  $(this).nextUntil('h3').each(function() {
     console.log($(this).text());
  });
});

必要に応じて、明示的な呼び出しなしでそれを行うこともできます.each()

$("h3").text(function(i,txt) {
  console.log(txt);
  $(this).nextUntil('h3').text(function(i,txt) {
    console.log(txt);
  });
});
于 2010-07-14T18:31:11.213 に答える
1

この.siblings()関数は「後続の兄弟」を意味するのではなく、「すべての兄弟」を意味します。最初の2つの<p>タグは、すべての<h3>タグの兄弟です。

于 2010-07-14T18:20:27.447 に答える
1

siblings()の代わりにnextAll()を使用してみてください。

于 2010-07-14T18:21:04.140 に答える