2015-11-04 87 views
4

在div容器中我想選擇所有標題並將其內容分組,直到下一個標題。這些塊應該有不同的背景顏色。如何選擇兩個相同元素之間的所有元素?

這是我在我的HTML有:

<div class="container"> 
    <h2></h2> 
    <p></p> 
    <p></p> 
    <ul></ul> 
    <h2></h2> 
    <p></p> 
    <p></p> 
    <p></p> 
    <h2></h2> 
    <p></p> 
    <p></p> 
    <p></p> 
</div> 

而我需要的是這樣的:

<div class="container"> 
    <div class="xy"> 
     <h2></h2> 
     <p></p> 
     <p></p> 
     <ul></ul> 
    </div> 
    <div class="xy"> 
     <h2></h2> 
     <p></p> 
     <p></p> 
     <p></p> 
    </div> 
    <div class="xy"> 
     <h2></h2> 
     <p></p> 
     <p></p> 
     <p></p> 
    </div> 
</div> 

我使用nextUntil()嘗試,但它並沒有爲我工作至今。

我將不勝感激任何幫助。

最佳, 羅賓

+0

你能告訴我們你寫了這一點JavaScript的?這樣,我們就可以看到您目前的做法出了什麼問題。 – Serlite

回答

8

該做的伎倆:

$('.container h2').each(function() { //for each h2 
 
    $(this) 
 
    .nextUntil('h2')     //get siblings until next h2, or all next siblings if no more h2 
 
    .addBack()       //include current h2 
 
    .wrapAll('<div class="xy"/>');  //wrap it 
 
}); 
 

 
$('pre').text($('.container').html()); //show it!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="container"> 
 
    <h2></h2> 
 
    <p></p> 
 
    <p></p> 
 
    <ul></ul> 
 
    <h2></h2> 
 
    <p></p> 
 
    <p></p> 
 
    <p></p> 
 
    <h2></h2> 
 
    <p></p> 
 
    <p></p> 
 
    <p></p> 
 
</div> 
 
     
 
<pre></pre>

+1

很好用,謝謝! – shroomlife

相關問題