13

当人们回答问题时,我会使用多个按钮。当一个人点击按钮时,我如何让按钮改变颜色?我不知道 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>

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

4

5 回答 5

27
$('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');
});
于 2013-04-26T16:20:20.860 回答
5

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

.ButtonClicked {
    background-color:red;
}

然后单击添加类:

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

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

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

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

这个 jsFiddle显示。只是思考的食物。

于 2013-04-26T16:19:47.507 回答
3

使用 CSS:

<style>
input[name=btnsubmit]:active {
color: green;
}
</style>
于 2013-04-26T16:21:25.773 回答
2

将此代码添加到您的页面:

<script type="text/javascript">
$(document).ready(function() {
   $("input[type='submit']").click(function(){
      $(this).css('background-color','red');
    });
});
</script>
于 2013-04-26T16:21:38.057 回答
1

您必须在您的文档头中包含来自 cdn 的 jquery 框架,例如:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>

然后你必须包含一个自己的脚本,例如:

(function( $ ) {

  $(document).ready(function(){
      $('input').click(function() {
          $(this).css('background-color', 'green');
      }
  });


  $(window).load(function() { 
  });

})( jQuery );

这部分是 $ 到 jQuery 的映射,所以实际上是 jQuery('selector').function();

(function( $ ) {

})( jQuery );

在这里您可以找到 jquery 的 api,其中列出了所有函数以及示例和说明:http ://api.jquery.com/

于 2013-04-26T16:25:31.827 回答