2015-08-28 285 views
0
<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <title>moockup< /title> 
     <style> 
      .yellowBackground { 
       background-color: yellow; 
      } 

      .redBackground { 
       background-color: red; 
      } 
     </style> 
    </head> 

    <body> 
     <button id="button" class="yellowBackground" id="thumb" >paina tästä< /button> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
     <script> 
      $(function() { 
       $("#button").click(function() { 
        changeThumb(); 
       }); 
      }); 
      function changeThumb() { 
       $("#thumb").toggleClass("yellowBackground redBackground"); 
      } 
     </script> 
    </body> 
</html> 

为什么这不起作用我想按下该按钮,它必须在每次点击后将其颜色更改为黄色和红色,我知道如何使用JavaScript,但我现在正在学习jQuery。按钮更改颜色

+2

你有你的按钮标记两个ID .... –

+0

啊哈我不能这样做呢?好吧,我现在要做什么? – waleedd32

回答

1

这里是一个解决方案的人:http://jsfiddle.net/leojavier/9psL0oa0/

<button class="yellowBackground" id="thumb" >test</button> 

CSS

.yellowBackground { 

background-color: yellow; 
} 

.redBackground { 

background-color: red; 
} 

JS

$("#thumb").click(function() { 

    $("#thumb").toggleClass("redBackground"); 

}); 
+0

希望这可以帮助... :) –

+0

toggleClass方法使您想要添加和删除的类名...默认情况下分配一个类,并且切换类应该覆盖默认类 –

+0

每个应该只有一个ID属性标签,并且它在整个文档中应该是唯一的 –

0

希望这会回答你的问题。 小提琴[http://jsfiddle.net/57vss22x/3/]

jQuery的

$(".place").click(function() { 
$(this).toggleClass("green"); 
}); 

CSS

.place { background-color: yellow; } 
.place.green { background-color: red; } 

HTML

<button id="button" class="place" id="thumb" >paina tästä</button> 
0

你不能有一个元素的多个id属性。

$("#button").click(function() { 
 
    changeThumb(); 
 
}); 
 
function changeThumb() { 
 
    $("#button").toggleClass("yellowBackground redBackground"); 
 
}
.yellowBackground { 
 
    background-color: yellow; 
 
} 
 
.redBackground { 
 
    background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<button id="button" class="yellowBackground">paina tästä</button>

+0

也谢谢你! – waleedd32