2012-02-24 17 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(); 
    }); 
}); 

これはコードが後に、単一のpタグの表示を切り替えますJS h1タグをクリックすると、h1タグが表示されます。しかし、私は連続したpタグの表示を切り替える必要があります(見出し1をクリックすると1から3まで)

これを行うにはどうすればよいですか?

+0

で導入あなたはdivの中にあなたの段落をラップする必要がありますが代わりにそれをトグルします。あなたが求めていることは可能ではありませんが、必要以上に複雑になるでしょう。 – bfavaretto

答えて

3

私はあなたのためにバイオリンを演奏:http://jsfiddle.net/hMsXz/2/

をここにクリックを保存するためのコード:

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

答えにコードを追加できますか?また '$(this).andSelf()'は何もせず、 'this'をコレクションに追加します(既に' this'を含んでいます)。 –

+0

ええ、私は「実験」からそれを忘れていましたが、すでに編集しました – mindandmedia

+0

@Rocket、編集のおかげで、私は別のタイプミスを発見しました... – mindandmedia

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(); 
    }); 
}); 
関連する問題