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" | 屬性選擇器組合 |
const $elements = $("h1, h2, p");classList.add() 批量處理掌握多選擇器配合類名操作,是編寫高效、可維護 jQuery 代碼的關鍵技能。