2013-08-26 54 views
1

我正在使用jQuery。我有以下的HTML片段:如何选择两个h2之间的所有元素

<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

但仍然无法确定如何去做我所需要的。

在此先感谢!

+2

什么是jQuery的你试过吗? – kunalbhat

+1

尝试使用['.nextUntil()'](http://api.jquery.com/nextUntil/)。就像'$('h2')。each(function(){console.log($(this).nextUntil('h2')。text());})' – Chad

+0

你有没有想过给每个H2一个类并使用.each()? – Brad

回答

3

我建议如下:

$('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 demo

虽然上述工作,为其预期用途,并说明nextUntil()(这绝对是在这种情况下使用的方法),我不确定我可以告诉你如何实现你的目标,因为你似乎有留下你的用例/需求比较模糊。

参考文献:

0

一个很好的解决办法是把你想在一个<div>标签与标识以检索内容,并使用jQuery以检索它像这样的内容:$('#divid').text()

+0

我同意@ cole-pileguard,因为他的解决方案最能解答您的具体问题。 – Oxymoron

相关问题