我正在使用jQuery。我有以下html片段:
<h1>Main Title</h1>
<h2>One header</h2>
<p>some text</p>
<p>more text</p>
<ul><li>a list</li></ul>
<h2>Another header</h2>
<a href="######">one link</a>
<h3>ddd</h3>
<p>eee</p>
<h2>Header 3<h2>
<p>This is a Paragraph</p>
我需要得到每个h2元素之间的内容,以便做这样的事情:
First Section text
some text
more text
Second section text
one link
ddd
eee
Third section text
This is a Paragraph
我已阅读此资源:http://www.tutorialspoint.com/jquery/jquery-selectors.htm
但仍然不知道如何做我需要的。
提前感谢!
我建议如下:
$('h2').each(function(){
var self = $(this),
// gets everything between the $(this) and the next 'h2' element:
contents = self.nextUntil('h2'),
/* creates a new div with which to wrap,
and inserts after the current $(this): */
newWrap = $('<div />').insertAfter(self);
// appends the contents to the new div element:
newWrap.append(contents);
});
JS Fiddle演示。
虽然以上内容适用于其预期用途,并说明了nextUntil()
(这肯定是本场景中使用的方法),但我不确定如何向您展示如何实现您的目标,因为您似乎对用例/需求含糊其辞。
参考文献:
- CCD_ 2
each()
insertAfter()
nextUntil()
我相信nextUntil方法就是您想要的。
http://api.jquery.com/nextUntil/
一个好的解决方案是将您希望检索的内容放在带有id的<div>
标记中,并使用jQuery检索其内容,如下所示:$('#divid').text()