在 jQuery 中 switchClass() 和 toggleClass() 方法之間有什麼區別?
switchClass() 用於切換元素上的類。使用它來用另一個類替換一個類。將 jQuery UI 庫新增到網頁以使用 switchClass()。
示例
你可以嘗試執行以下程式碼來學習如何使用 switch 類 -
<html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="demo1">One</a> <a href="#" class="demo2">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html>
切換類
如果你想在類之間切換,可以使用 toggleClass()。可以給選中的元素新增或刪除類。
示例
你可以嘗試執行以下程式碼來學習如何切換類 -
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h1, p").toggleClass("blue"); }); }); </script> <style> .blue { color: blue; } </style> </head> <body> <h1>Heading 1</h1> <p>This is demo text.</p> <button>Toggle</button> </body> </html>
廣告