在Click上切换行为

时间:2009-08-14 08:42:22

标签: jquery

如何在CLick上切换行为。当我点击按钮时,我希望它将其更改为红色。当我再次点击时,它应该变成蓝色等等

3 个答案:

答案 0 :(得分:3)

使用.toggle

e.g

$("#inputId").toggle(
      function () {
        $(this).addClass('someClass');
      },
      function () {
        $(this).addClass('differentClass');
      }
);

答案 1 :(得分:1)

HTML:

<input id="MyButton" type="button" value="Click me" class="Color1" />

JQuery的:

<script type="text/javascript">
    $(document).ready(function() {
        $("#MyButton").click(function() {
            if ($(this).attr("class") == "Color1") {
                $(this).attr("class", "Color2");
            }
            else {
                $(this).attr("class", "Color1");
            }
        });
    });
</script>

答案 2 :(得分:0)

<!-- To change this template, choose Tools | Templates and open the template in the editor. --> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title></title>
  <script src="jquery/jquery.js" language="javascript" type="text/javascript"></script> 

  <script> 
    $(document).ready(function(){
      $("button").click(function () {
        $('#blue').toggleClass("red");
      });
    });
  </script> 

  <style> 
    div { 
      margin:3px;  
      width:50px;  
      position:absolute;  
      height:50px;  
      left:10px;  
      top:30px;  
      background-color:yellow;  
    }  
    div.blue{ background-color: blue; }  
    div.red { background-color:red; }  
  </style> 

</head> 
<body> 

  <button>Start</button> 

  <div id="blue"></div>

</body>
</html>