標籤為例
有時需一次隱藏某類型的所有標籤(如所有段落 `
`、所有圖片 ``)。jQuery 標籤選取器 `
tagName` 配合 `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() {
$("p").hide(); // 隱藏所有 <p> 標籤
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</body>
</html>
// 隱藏所有圖片
$("img").hide();
// 隱藏所有連結
$("a").hide();
// 隱藏所有輸入框
$("input").hide();
// 隱藏所有 div 區塊
$("div").hide();
避免影響全站,建議限定在特定容器內:
// 僅隱藏 .content 區塊內的段落
$(".content p").hide();
// 僅隱藏表單內的輸入框
$("form input").hide();
:visible / :hidden 偽類// 只隱藏目前可見的段落
$("p:visible").hide();
// 只顯示目前隱藏的段落
$("p:hidden").show();
標籤選取器會遍歷全文件,大型頁面建議:
標籤選取器雖方便,實務上多搭配上下文限定使用,以免誤傷非目標元素。