ID 選取器 `#id` 是 jQuery 中效能最好、語意最明確的選取方式(因為 ID 在頁面應唯一)。搭配 `hide()` 可精準隱藏單一元素。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#test").hide(); // 僅隱藏 id="test" 的元素
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p id="test">This is another paragraph. jb51.net</p>
<button>Click me</button>
</body>
</html>
| 選取器 | 匹配數量 | 適用場景 |
|---|---|---|
#test | 0 或 1 個 | 唯一識別元素 |
.test | 0 ~ N 個 | 群組相同樣式/行為元素 |
p | 0 ~ N 個 | 針對標籤類型批次操作 |
var $el = $("#test");
if ($el.length) { $el.hide(); }
$("#id1, #id2, #id3").hide(); // 多重選取器,以逗號分隔
$("#test").fadeOut(400, function() {
$(this).remove(); // 動畫完成後從 DOM 移除
});
#id` 僅返回第一個匹配元素。掌握 ID 選取器與 `hide()` 組合,是前端開發最基礎也最實用的技能之一。