隱藏元素是 jQuery 最基礎的操作之一,一行 hide() 就足夠。以下範例示範點擊哪個元素,就讓哪個元素消失。
<!DOCTYPE html>
<html>
<head>
<style>
div {
background: #ece023;
width: 30px;
height: 40px;
margin: 2px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div>a</div>
<div>b</div>
<div>c</div>
<div>d</div>
<div>e</div>
<div>f</div>
<script>
$("div").click(function () {
$(this).hide(1000);
});
</script>
</body>
</html>
$("div") 選到的是全部六個 div,但回呼裡的 $(this) 只指向「目前被點擊的那一個」。這正是事件處理中最實用的模式:用同一份程式碼服務多個元素,靠 this 分辨是誰觸發的。
hide(1000) 中的 1000 是毫秒,代表用一秒的時間滑動收起;不帶參數則立即隱藏。反向操作是 show(),若只想切換狀態,用 toggle() 更簡潔。
hide 只是藏起來:元素仍在 DOM 中,只是被設為 display: none,內容依然可被人從原始碼看到。因此它適合控制版面,不適合用來保護敏感資料。
動畫會累積:連續快速點擊時,動畫會排隊執行看起來很卡頓。加上 .stop() 就能中止前一輪動畫,例如 $(this).stop(true).hide(1000)。
動態產生的元素:若 div 是 Ajax 之後才加入的,要在文件層級用事件委派:$(document).on("click", "div", function(){ ... }),否則新元素不會有點擊效果。
另外,範例中的 jQuery 路徑用了 jquery-latest,正式環境請改為明確版本號,避免上游更新造成非預期的行為變化。