常見需求:使用者點擊按鈕後,該按鈕自行隱藏。jQuery 的 hide() 搭配 $(this) 即可輕鬆達成。
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$(this).hide(); // 隱藏觸發點擊的按鈕本身
});
});
</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>
$(document).ready():確保 DOM 載入完成後再綁定事件。$("button"):選取所有 `$(this):在事件處理函式中指向**觸發事件的該個 DOM 元素**。.hide():將元素的 CSS `display` 設為 `none`,佔位空間也會消失。$(this).fadeOut(300); // 300ms 淡出再隱藏
$(this).hide(200, function() {
console.log("按鈕已隱藏");
});
若有多個按鈕皆使用 `$("button")` 選取,點擊任一個會隱藏**所有**按鈕。正確做法:
// 方式一:各按鈕綁定各自事件
$("#btnA").click(function() { $(this).hide(); });
$("#btnB").click(function() { $(this).hide(); });
// 方式二:事件代理(動態新增按鈕也生效)
$(document).on("click", ".hide-me", function() {
$(this).hide();
});
掌握 `$(this)` 語境,就能靈活處理各種「自我隱藏」互動需求。