简体   繁体   English

删除按钮单击jQuery的CSS样式?

[英]remove css style on button click jquery?

I am trying to change the colour of buttons if they're clicked using jquery. 我正在尝试更改使用jquery单击的按钮的颜色。

my code bellow works and it will add the expand class to the clicked button. 我的代码如下工作,它将扩展类添加到单击的按钮。 but I need to know how I can remove the class and add the old class to it if another button is clicked and visa versa. 但是我需要知道如何在单击另一个按钮时删除该类并向其中添加旧类,反之亦然。

this is my code now: 现在这是我的代码:

$(".mybtn").click(function(){
  $(this).removeClass( "mybtn" ).addClass('expand');

});  

and the html is like this: 和HTML是这样的:

<button name='mybtn' id='mybtn' class='mybtn' value='1'>1</button>
<button name='mybtn' id='mybtn' class='mybtn' value='2'>2</button>
<button name='mybtn' id='mybtn' class='mybtn' value='3'>3</button>

and the css is a simple css with background color: CSS是具有背景颜色的简单CSS:

.mybtn{
background-color:#fff;
}

.expand{
background-color:#000;
}

any help would be appreciated. 任何帮助,将不胜感激。

Reset all the "expand" class objects first: 首先重置所有“扩展”类对象:

$(".mybtn").click(function(){
   // remove expand class and add original mybtn class
  $(".expand").removeClass( "expand").addClass("mybtn");

  $(this).removeClass( "mybtn" ).addClass('expand');

}); 

See working example at Fiddle 请参阅小提琴上的工作示例

$('.mybtn').toggle(function () {
    $(".mybtn").removeClass("mybtn").addClass("expand");
}, function () {
    $(".mybtn").removeClass("expand").addClass("mybtn");
});

try this : 尝试这个 :

$(".mybtn").each(function(){    
   $(this).click(function(el, ev){
      $('button#mybtn').addClass('mybtn').removeClass('expand'); 
      $(this).removeClass( "mybtn" ).addClass('expand');     
   }); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM