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