javascript JQUERY - 单击后将 CSS 类添加到 BUTTON 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17092067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:03:38  来源:igfitidea点击:

JQUERY - add CSS class to BUTTON element after click

javascriptjqueryhtmlcss

提问by Roy H

I want to change the background color of a button permanently after it is clicked. Using the following code the color only changes while the button is active/being clicked. Once the mouse button is released the added "clicked" class is no longer applied to the element.

我想在单击后永久更改按钮的背景颜色。使用以下代码,颜色只会在按钮处于活动状态/被点击时改变。释放鼠标按钮后,添加的“单击”类不再应用于元素。

Applying the following code to an INPUT tag instead of a BUTTON tag works the way I need it to. However, I'm using a BUTTON tag since I want the value to be different from the text inside the button.

将以下代码应用到 INPUT 标记而不是 BUTTON 标记可以按照我需要的方式工作。但是,我使用的是 BUTTON 标记,因为我希望该值与按钮内的文本不同。

What do I need to change?

我需要改变什么?

-- Thanks.

- 谢谢。

 HTML
 <button class="inactive" value="test">Button</button>

 CSS
 .inactive {background-color:gray;}
 .clicked {background-color:orange;}

 JS
 $(document).ready(function(){
      $('button').click(function(){
           $(this).addClass('clicked');
      });
 );

回答by Dallas

The only problem is that you are missing a curly brace: http://jsfiddle.net/AaKuf/

唯一的问题是您缺少大括号:http: //jsfiddle.net/AaKuf/

 $(document).ready(function(){
      $('button').click(function(){
           $(this).addClass('clicked');
      });
 }); //<==here

回答by ayyp

$('button.inactive').click(function() {
    $(this).removeClass('inactive').addClass('clicked');
});

Should do the trick. This will clear the old class away from the button and give it the proper .clickedclass. If the colour is resetting after using this solution, then the problem is elsewhere in your code.

应该做的伎俩。这将从按钮清除旧类并为其提供适当的.clicked类。如果使用此解决方案后颜色重置,则问题出在代码的其他地方。

回答by Seiyria

$('button').mouseup(function() { 
    $(this).removeClass('clicked').addClass('inactive');
}