2013-08-26 55 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

相關問題