2012-02-24 20 views
4

請通過下面的代碼片段看起來 -如何使用jQuery獲取連續的元素?

HTML

<div class="aclass"> 
    <h1>This is heading one</h1> 
    <p>This is paragraph one, this will be hidden automatically</p> 
    <p>This is paragraph two, this will be hidden automatically</p> 
    <p>This is paragraph three, this will be hidden automatically</p> 
    <h1>This is heading two</h1> 
    <p>This is paragraph four, this will be hidden automatically</p> 
    <p>This is paragraph five, this will be hidden automatically</p> 
</div> 

CSS

.aclass p {display:none;} 

JS

$(document).ready(function(){ 
    $('.aclass h1').click(function(){ 
     $(this).next('p').toggle(); 
    }); 
}); 

這個js代碼切換單P標籤後顯示點擊h1標籤時的h1標籤。但我需要切換顯示連續的p標籤(點擊標題之一時爲1到3)

什麼應該是jQuery代碼這樣做?

+0

你應該包裝在一個div段落,然後切換。並不是說你所要求的是不可能的,但它會比所需要的更加複雜。 – bfavaretto 2012-02-24 21:45:13

回答

3

我拉了小提琴爲您提供:http://jsfiddle.net/hMsXz/2/

這裏保存點擊代碼:

$('.aclass h1').click(function(){ 
    $(this).nextUntil('h1','p').toggle(); 
}); 
+1

你可以將代碼添加到你的答案?另外,'$(this).andSelf()'什麼都不做,它將'this'加入集合(已經包含'this')。 – 2012-02-24 21:48:35

+0

是的,我忘了從一個'實驗',編輯已經 – mindandmedia 2012-02-24 21:50:35

+0

@火箭,感謝編輯,我發現了另一個錯字... – mindandmedia 2012-02-24 22:02:31

4

使用.nextUntil

$('.aclass h1').click(function() { 
    $(this).nextUntil('h1', 'p').toggle(); // Selects all p tags after the h1 
              // stops when it hits an h1 
});​ 

DEMO:http://jsfiddle.net/dt7LH/

2

我猜你的意思是要展開/摺疊下方點擊<h1>所有<p>標籤?

使用nextUntil('h1')選擇所有同級元素,直到<h1>標記。

1

使用.nextUntil中的jQuery 1.4中引入

$(document).ready(function(){ 
    $('.aclass h1').click(function(){ 
     $(this).nextUntil('h1').toggle(); 
    }); 
});