2017-03-22 7 views
0

これは、ボタンクリックイベントを実行して複数のリストで選択したアイテムを制御するHTMLです。しかし 異なるリストから同時にアイテムを選択

$('#button').click(function(){ 
 
    var $next = $('.section.selected').removeClass('selected').next('.section') 
 
    if ($next.length) { 
 
     $next.addClass('selected'); 
 
    } 
 
    else { 
 
     $(".section:first").addClass('selected'); 
 
    } 
 
}); 
 

 
//On click I select next div with same class and remove selected from previous. 
 
//How to loop? After 3 is selected, I want it to go to one again.
.selected { background:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="all"> 
 
    <div class="section selected">ONE</div> 
 
    <div class="section">TWO</div> 
 
    <div class="section">THREE</div> 
 
</div> 
 
<div id="all"> 
 
    <div class="section selected">ONE</div> 
 
    <div class="section">TWO</div> 
 
    <div class="section">THREE</div> 
 
</div> 
 
<br /> 
 
<a href="javascript:;" id="button">CLICK</a>

、項目は同じクラス名を使用しているので、最後に、スクリプトは/最初の最後の項目があるか決めることができません。

誰でも私にアイデアを教えてもらえますか?これは代わりに$(".section:first-child").addClass('selected')アイテムを得るためにあなたのelse条件

+0

ああをチェックし、私は、感謝を保存するのを忘れ、クラスにそれらを変更しました。 – A7bert

答えて

1

で、その上first-childlast-childなどクエリを使用

+0

このような単純なこと.....実際には何ですか?ありがとうございました。 – A7bert

+0

@ A7bert私が提供したリンクには、すべてのjQueryセレクタが含まれています。それを読む時間が必要です。役に立つと分かるかもしれません。 –

+0

もう一度、ありがとう、私はそれを読んでいます。ありがとうございました! – A7bert

1

使用。

よりdetalsについては

jQuery API Documentation

+0

ありがとうございます...私は違いが何かを理解できません...しかし、あなたの高速回答に感謝します。 – A7bert

+1

こんにちは、ここで違いを見つけることができます [jQuery最初の子と](http://stackoverflow.com/a/2946217/5648904) –

関連する問題