最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add and remove class onClick action - Stack Overflow

programmeradmin1浏览0评论
 <button class="fbutton btn pull-right filterevents " id="one" >School Events</button>
  <button class="fbutton btn pull-right filterevents" id="two" >Zone Events</button>
  <button class="fbutton btn pull-right filterevents" id="three" >My Events</button>

I need to add class "selected" to specific button onClick.

my code is

$("#one").click(function(e) {
                $(this).addClass("fcurrent");
                $("#two").removeClass("fcurrent");
                 $("#three").removeClass("fcurrent");
   });

if i use instead of id to class like following ,

$(".fbutton").click(function(e) {
                    $(this).addClass("fcurrent");
       });

then how to remove the fcurrent class to another two buttons

 <button class="fbutton btn pull-right filterevents " id="one" >School Events</button>
  <button class="fbutton btn pull-right filterevents" id="two" >Zone Events</button>
  <button class="fbutton btn pull-right filterevents" id="three" >My Events</button>

I need to add class "selected" to specific button onClick.

my code is

$("#one").click(function(e) {
                $(this).addClass("fcurrent");
                $("#two").removeClass("fcurrent");
                 $("#three").removeClass("fcurrent");
   });

if i use instead of id to class like following ,

$(".fbutton").click(function(e) {
                    $(this).addClass("fcurrent");
       });

then how to remove the fcurrent class to another two buttons

Share Improve this question edited Jun 16, 2014 at 11:46 Okky 10.5k15 gold badges77 silver badges123 bronze badges asked Jun 16, 2014 at 11:44 Dhanush BalaDhanush Bala 1,1321 gold badge14 silver badges28 bronze badges
Add a comment  | 

6 Answers 6

Reset to default 8

Try this.

$(".fbutton").click(function (e) {
$(this).addClass("fcurrent").siblings().removeClass("fcurrent");
});

DEMO

$(".fbutton").click(function(e) {
    $(".fbutton").removeClass("fcurrent");
    $(this).addClass("fcurrent");
});

You can first remove .fcurrent class from all button elements , then add your class to current button like this:

$(".fbutton").click(function(e) {
    $(".fbutton").removeClass("fcurrent");
    $(this).addClass("fcurrent");
}

If you only use the fcurrent class for these buttons, you could remove the class from any other button that has it before adding it to the current button:

$('.fbutton').click(function(e) {
    $('.fcurrent').removeClass('fcurrent');
    $(this).addClass('fcurrent');
});

You can first remove the class fcurrent from all buttons and then add it again to the one you clicked.

$(".fbutton").click(function(e) {
   $(".fbutton").removeClass("fcurrent");
   $(this).addClass("fcurrent");
});

You can try this -

$(".fbutton").click(function(e) {
    $(".fbutton").removeClass("fcurrent");
    $(this).addClass("fcurrent");
});
发布评论

评论列表(0)

  1. 暂无评论