javascript - 嵌套每个循环导致问题

标签 javascript jquery each

您好 – 我的问题最好用预期输出和实际输出进行总结。使用以下 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

谢谢。

最佳答案

因为 siblings() 选择了所有 sibling ,包括之前的和之后的所有 sibling 。我想你需要 nextAll() :

Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.


Demo

$("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

关于javascript - 嵌套每个循环导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3249144/

相关文章:

javascript - Django Rest 框架 + ReactJS : Whats wrong with my API?

javascript - 在 Redux Reactjs 中输入内容时 TextField 失去焦点

javascript - 不再显示此页面(JQUERY cookie)

javascript - 将div内的元素排成一条直线

arrays - 如何在 SCSS 中获取数组的 $values?

jQuery - 延迟向数组内的元素添加类

jquery - 使用 jQuery 迭代 select 元素中的选项

javascript - 取消 ExtJS 组件的事件

javascript - 从 https 证书中读取关键扩展

javascript - 在其他循环内延迟循环