jQuery改变按钮颜色onclick

新手上路,请多包涵

当人们回答问题时,我会使用多个按钮。当一个人点击按钮时,我如何让按钮改变颜色?我不知道 jQuery,有人告诉我这是最好的选择。

这是我的 HTML 部分的代码:

 <div style="text-align: center;"><span style="line-height: 18px; font-family: Arial, Helvetica, sans-serif; font-size: 24px;">In the past three months, how often have you used marijuana?<br />
<p><input type="submit" value=" Never " name="btnsubmit" id="answer" style="width: 200px;" /></p>
<p><input type="submit" value=" Once or Twice " name="btnsubmit" id="answer" style="width: 200px;" /></p>
<p><input type="submit" value=" Monthly " name="btnsubmit" id="answer" style="width: 200px;" /></p>
<p><input type="submit" value=" Daily or Almost Daily " name="btnsubmit" id="answer" style="width: 200px;" /></p>
</span></div>
<div>
<p style="text-align: right;"><a onclick="window.open(this.href,'_parent');return false;" href="/mobile/Static2.aspx"><input type="submit" value=" Next " name="btnsubmit" style="width: 100px;" /></a></p>
</div>

我对编码真的很陌生,所以任何形式的帮助都将不胜感激!

原文由 Sean6971 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
2 个回答
$('input[type="submit"]').click(function(){
$(this).css('color','red');
});

使用类,Demo:- https://jsfiddle.net/BX6Df/

    $('input[type="submit"]').click(function(){
          $(this).addClass('red');
});

如果你想每次点击切换颜色,你可以试试这个:- https://jsfiddle.net/SMNks/

 $('input[type="submit"]').click(function(){
  $(this).toggleClass('red');
});

.red
{
    background-color:red;
}

更新了您评论的答案。

https://jsfiddle.net/H2Xhw/

 $('input[type="submit"]').click(function(){
    $('input[type="submit"].red').removeClass('red')
        $(this).addClass('red');
});

原文由 PSL 发布,翻译遵循 CC BY-SA 4.0 许可协议

我只想创建一个单独的 CSS 类:

 .ButtonClicked {
    background-color:red;
}

然后点击添加类:

 $('#ButtonId').on('click',function(){
    !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});

这应该做你正在寻找的东西,由 这个 jsFiddle 显示。如果您对 ? 等的逻辑感到好奇,它称为 三元(或条件)运算符,它只是执行简单 if 逻辑以检查类是否已添加的简洁方法.

您还可以通过切换类来创建具有“开/关”切换感觉的能力:

 $('#ButtonId').on('click',function(){
    $(this).toggleClass('ButtonClicked');
});

这个 jsFiddle 显示。只是值得深思。

原文由 PlantTheIdea 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题