Javascript 如何通过jQuery获取P元素直到下一个H2元素?
我有这个HTML结构:Javascript 如何通过jQuery获取P元素直到下一个H2元素?,javascript,jquery,html,Javascript,Jquery,Html,我有这个HTML结构: <h2>title 1</h2> <p>bla</p> <p>bla</p> <h2>title 2</h2> <p>bla</p> <p>blabla</p> <p>bla</p> <h2>title 3</h2> <p>bla</p> 标题1 布拉 布拉
<h2>title 1</h2>
<p>bla</p>
<p>bla</p>
<h2>title 2</h2>
<p>bla</p>
<p>blabla</p>
<p>bla</p>
<h2>title 3</h2>
<p>bla</p>
标题1
布拉
布拉
标题2
布拉
布拉布拉
布拉
标题3
布拉
H2之后p元素的数量是多种多样的
H2
和p
元素是我要寻找的一组元素。是否有任何解决方案来获取这组元素,或以任何其他方式来查找H2(或文档末尾)之间的P所有元素
我被选中了.nextAll()
函数,但它找到了所有下一个p元素,直到下一个H2。一个选项是:
var set = $('h2').map(function() {
return $(this).add( $(this).nextUntil('h2') );
});
上面的答案假设在每个h2
元素之后只有p
元素,它创建了一个jQuery集合的jQuery集合。如果它不能完全满足您的要求(不只是获取p
元素),则需要使用不同的逻辑过滤下一个元素,直到下一个h2
元素:
return $(this).add( $(this).nextUntil('h2').filter('p') );
一种选择是:
var set = $('h2').map(function() {
return $(this).add( $(this).nextUntil('h2') );
});
上面的答案假设在每个h2
元素之后只有p
元素,它创建了一个jQuery集合的jQuery集合。如果它不能完全满足您的要求(不只是获取p
元素),则需要使用不同的逻辑过滤下一个元素,直到下一个h2
元素:
return $(this).add( $(this).nextUntil('h2').filter('p') );
要使每组
p
元素位于h2
元素或端点之间,请使用以下命令:
var $h2 = $("h2"); // get the h2 elements
$h2.each(function() { // for each one of them ...
var $p = $(this).nextUntil("h2", "p"); // get the p elements untill the next h2 element or the end
// do stuff with this group of p elements
}
要使每组
p
元素位于h2
元素或端点之间,请使用以下命令:
var $h2 = $("h2"); // get the h2 elements
$h2.each(function() { // for each one of them ...
var $p = $(this).nextUntil("h2", "p"); // get the p elements untill the next h2 element or the end
// do stuff with this group of p elements
}
有一个
.nextUntil()
函数。你检查过了吗?一旦你找到了相关的元素,你想用它们做什么?顺便说一句:。h2元素之间只有段落吗?@ibrahimmahrir:是的,只有段落它们有一个.nextUntil()
函数。你检查过了吗?一旦你找到了相关的元素,你想用它们做什么?顺便问一下:。h2元素之间只有段落吗?@ibrahimmahrir:是的,只有段落