简体   繁体   English

单击然后取消单击jQuery按钮不起作用

[英]click then unclick jquery button not working

I'm trying to make a button which on one click it changes it's color, and on another click it returns to it's original form. 我正在尝试制作一个按钮,单击该按钮可以更改其颜色,而单击另一按钮则可以恢复其原始形式。 something like clicked and unclicked. 诸如单击和未单击之类的东西。

I added a JSfiddle for you to look at it. 我添加了一个JSfiddle供您查看。 https://jsfiddle.net/dw5y5xLx/3/ https://jsfiddle.net/dw5y5xLx/3/

$('.genM').click(function() {

$('.genM').removeClass('selected');


$(this).addClass('selected');

});

thanks! 谢谢!

also, is there a way doing that by only using CSS HTML? 另外,有没有办法仅使用CSS HTML?

Thanks. 谢谢。

$('.genM').click(function() {
    $(this).toggleClass('selected');
});

I have updated the js fiddle for you, please check ( https://jsfiddle.net/dw5y5xLx/15/ )! 我已经为您更新了js小提琴,请检查( https://jsfiddle.net/dw5y5xLx/15/ )!

jQuery hasClass function can be helpful jQuery hasClass函数可能会有所帮助

$('.genM').click(function() {

    if($(this).hasClass('selected')){
            $(this).removeClass('selected');
    }else{
        $(this).addClass('selected');
    }

});

IDEA: 理念:

Is there a way doing that by only using CSS HTML? 有没有办法只使用CSS HTML?

Yes, there is a way how u could achieve that just by pure CSS and HTML. 是的,有一种方法可以仅通过纯CSS和HTML来实现。 But, if you dont want to use js, you must have an HTML element that is able to keep the "pressed" or "unpressed" state all by itself, without js. 但是,如果您不想使用js,则必须具有一个HTML元素,该元素能够在没有js的情况下独自保持“按下”或“未按下”状态。

However, there is no such an HTML element, so you have to use something simmilar: Checkbox 但是,没有这样的HTML元素,因此您必须使用类似的用法: 复选框

<input type="checkbox"> have "checked" and "unchecked" state and it is practicaly the same as "pressed" or "unpressed". <input type="checkbox">具有“已选中”和“未选中”状态,实际上与“已按下”或“未按下”相同。


SOLUTION: 解:

The trick is to stylize the ckeckbox with CSS so it visually appears as a pressed or unpressed button. 诀窍是使用CSS风格化ckeckbox,使其在视觉上显示为按下或未按下的按钮。 Here is an example how checkbox can be stylised - you need to modify the CSS in order to appear it like a button, not a toggle switch! 这是一个如何样式化复选框的示例 -您需要修改CSS才能使其像按钮一样显示,而不是拨动开关!

You will want to use CSS selectors like this (as shown in example): 您将要使用像这样的CSS选择器(如示例所示):

input[type="checkbox"]:checked { ... },
input[type="checkbox"]:checked + .slider { ... },

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

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