嵌套的Each循环导致问题

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

谢谢。


我很困惑你为什么要担心检查下一个h3。如果<p>标签在<h3>内部,嵌套循环将自动处理到达<p>选择器末尾时转到下一个<h3>的情况。 - JasCav
1
@Jason:p元素不在h3元素内。它们甚至不被允许在那里。 - Felix Kling
@Felix - 哇,我是个新手。哈哈,我甚至知道这一点,但还是问了愚蠢的问题。感谢您的澄清(也感谢您没有把我碾过去)。 - JasCav
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

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);
  });
});

1

.siblings()函数并不意味着“后续兄弟”,而是指“所有兄弟”。前两个<p>标签是所有<h3>标签的兄弟。


1

尝试使用nextAll()而不是siblings()。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接