萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 為多個不同元素同時添加 Class 樣式方法詳解

jQuery 多選擇器批量添加 Class 實戰技巧

jQuery 強大的選擇器引擎允許我們用逗號分隔的多選擇器一次選中不同類型的元素,配合 addClass() 即可實現為不同標籤統一添加樣式類,大幅簡化代碼。

多選擇器語法

// 選中 h1、h2、p 三種標籤
$("h1, h2, p").addClass("blue");

// 選中不同類型元素分別添加不同 class
$("h1, h2, p").addClass("blue");
$("div").addClass("important");

完整演示範例

<!DOCTYPE html>
<html>
<head>
  <script src="js/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      $("button").click(function(){
        $("h1, h2, p").addClass("blue");
        $("div").addClass("important");
      });
    });
  </script>
  <style type="text/css">
    .important { font-weight: bold; font-size: xx-large; }
    .blue { color: blue; }
  </style>
</head>
<body>
  <h1>Heading 1</h1>
  <h2>Heading 2</h2>
  <p>This is a paragraph.</p>
  <p>This is another paragraph.</p>
  <div>This is some important text!</div>
  <br>
  <button>Add classes to elements</button>
</body>
</html>

進階選擇器技巧

選擇器說明
".class1, .class2"選中多個 class
"#id1, #id2"選中多個 ID
"div, .highlight"混合標籤與 class
"input[type=text], textarea"屬性選擇器組合

性能優化建議

  • 避免過度複雜的選擇器,優先使用 ID 或 class
  • 頻繁操作時緩存 jQuery 對象:const $elements = $("h1, h2, p");
  • 大量元素操作考慮原生 classList.add() 批量處理

掌握多選擇器配合類名操作,是編寫高效、可維護 jQuery 代碼的關鍵技能。

copyright © 萬盛學電腦網 all rights reserved