歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery動態添加和刪除class屬性

jQuery動態添加和刪除class屬性

日期:2017/3/1 10:19:55   编辑:Linux編程

在用jQuery時,遇到一個問題,就是如何動態得添加和刪除class的屬性,下面是我的解決代碼:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>測試</title>
  6. <script type="text/javascript" src="jquery-1.7.2.js"></script>
  7. <script type="text/javascript">
  8. $(document).ready(function(){
  9. $("button").click(function(){
  10. $("p:first").addClass("intro");
  11. $("p:first").removeClass("default");
  12. });
  13. });
  14. </script>
  15. <style type="text/css">
  16. .intro
  17. {
  18. font-size:120%;
  19. color:red;
  20. }
  21. .default
  22. {
  23. font-size:16;
  24. color:#0F9;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <h1>This is a heading</h1>
  30. <p class="default">This is a paragraph.</p>
  31. <p>This is another paragraph.</p>
  32. <button>向第一個 p 元素添加一個類並刪除一個類</button>
  33. </body>
  34. </html>

效果如下:

點擊前:

點擊後:

Copyright © Linux教程網 All Rights Reserved