Jquery 单击时切换行为

Jquery 单击时切换行为,jquery,Jquery,如何在单击时切换bhavior。当我点击一个按钮时,我想让它变成红色。当我再次单击时,它应该变成蓝色,依此类推 e、 g 使用 e、 g HTML: JQuery: <script type="text/javascript"> $(document).ready(function() { $("#MyButton").click(function() { if ($(this).attr("class") == "Color1")

如何在单击时切换bhavior。当我点击一个按钮时,我想让它变成红色。当我再次单击时,它应该变成蓝色,依此类推

e、 g

使用

e、 g

HTML:


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>

$(文档).ready(函数(){
$(“#我的按钮”)。单击(函数(){
if($(this.attr(“类”)=“Color1”){
$(this.attr(“class”,“Color2”);
}
否则{
$(this.attr(“class”,“Color1”);
}
});
});
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>

$(文档).ready(函数(){
$(“#我的按钮”)。单击(函数(){
if($(this.attr(“类”)=“Color1”){
$(this.attr(“class”,“Color2”);
}
否则{
$(this.attr(“class”,“Color1”);
}
});
});

$(文档).ready(函数(){
$(“按钮”)。单击(函数(){
$('蓝色').toggleClass(“红色”);
});
});
div{
保证金:3倍;
宽度:50px;
位置:绝对位置;
高度:50px;
左:10px;
顶部:30px;
背景颜色:黄色;
}  
div.blue{背景色:蓝色;}
div.red{背景色:红色;}
开始

$(文档).ready(函数(){
$(“按钮”)。单击(函数(){
$('蓝色').toggleClass(“红色”);
});
});
div{
保证金:3倍;
宽度:50px;
位置:绝对位置;
高度:50px;
左:10px;
顶部:30px;
背景颜色:黄色;
}  
div.blue{背景色:蓝色;}
div.red{背景色:红色;}
开始

second function()后面的逗号在某些浏览器中会导致语法错误。@Ryan Berger yeah ie不喜欢它-修复了second function()后面的逗号在某些浏览器中导致语法错误。@Ryan Berger yeah ie不喜欢它-修复类型为什么您要在DOM中选择一个单独的div,而不是使用
e.target
this
在按钮上设置它?为什么您要在DOM中选择一个单独的div,而不是使用
e.target
在按钮上设置它
这个
<!-- 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>