4

Hello – My question is best summarize with the intended output and the real output. Any clue why it's doing this, using the following HTML and JS code?

HTML Code:

<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 Code:

$(".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());
    }
  });
});

Intended Output:

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

Real (Unintended) Output:

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

Thanks.

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

If there are no more siblings after the last <p> element, I guess I'd use .nextUntil('h3') instead:

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

If you wanted, you could even do it without the explicit calls to .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()函数并不意味着“后续兄弟姐妹”,而是意味着“所有兄弟姐妹”。前两个<p>标签是所有标签的兄弟<h3>

于 2010-07-14T18:20:27.447 回答
1

尝试使用 nextAll() 而不是兄弟姐妹()。

于 2010-07-14T18:21:04.140 回答