2017-01-05 7 views
0

私は、単一のボタンは以下のコードを使用してボタンをオフに移動した後にアクティブに滞在することができます:jQueryのは、アクティブな押されたボタンを作成し、アクティブでない他のすべてのボタンは

$('.btn').click(function(){ 
     if($(this).hasClass('active')){ 
      $(this).removeClass('active') 
     } else { 
      $(this).addClass('active') 
     } 
    }); 

しかし、私はまた、ページ上の他のすべてのボタンを作りたいです非アクティブ。私は以下を試しましたが、すべての非アクティブをクリック機能の外にする必要があるという表現がありました。クリック機能の内部でループを実行して全体のボタンを反復するにはどうすればよいですか?

答えて

1

.each()を使用して反復処理する必要はありません。ボタンクリックで.activeクラスを削除し、クリックされたボタンに適用するだけです。

また、非アクティブなクラスをボタンに適用するだけでなく、1つのボタンをクリックすると、非アクティブなクラスがクリックされなかったボタンに適用されます。 (この)ではない使用

$(document).ready(function(){ 
 
    $('.btn').click(function(){ 
 
    $('.btn').removeClass('active').addClass('inactive'); 
 
    $(this).removeClass('inactive').addClass('active'); 
 
    }); 
 
})
.btn{color:white} 
 
.active{background:green} 
 
.inactive{background:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button type="button" class="btn inactive">test 1</button> 
 
<button type="button" class="btn inactive">test 2</button> 
 
<button type="button" class="btn inactive">test 3</button>

0

私が問題として理解しているのは、すべてのボタンクラスをアクティブにしてボタンがそのクラスを持っているかどうかを確認することです。

$(function(){ 
$('.btn').click(function(){ 
    var active = $(this).hasClass('active'); 
    //make all inactive-doesn't work 
    $('.btn').each(function() { 
     if($(this).hasClass('active')){ 
      $(this).removeClass('active') 
     } 
    }); 

    if(active){ 
     $(this).removeClass('active') 
    } else { 
     $(this).addClass('active') 
    } 
}); 
}); 
0
$('.btn').click(function(){ 
    // remove all the active class 
    $('.btn').each(function() { 
     $(this).removeClass('active') 
    }); 
    //then the click button add class active 
    if($(this).hasClass('active')){ 
     $(this).removeClass('active') 
    } else { 
     $(this).addClass('active') 
    } 

});:あなたはすでにあなたはこのようなすべてのボタンのためにそれを削除する前に、あなたは真または偽の変数として保存することができ、前にそれを削除したので、それは意味がありません

1

Working fiddle

$('.btn').click(function() { 
     if ($(this).is("active")) 
     $('.btn').not(this).removeClass('active'); 
     else 
     $(this).addClass('active'); 
     $('.btn').not(this).removeClass('active'); 
    }); 
+0

をおかげで、これはうまく動作しますが、gavgrifからの答えは少し短いと簡単ですので、私は答えとしてことを選びました –

関連する問題