// 事件委託:綁定在父容器,處理動態新增元素
$('#container').on('click', 'div', function() {
$(this).hide(1000); // 1 秒淡出動畫
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 點擊隱藏演示</title>
<style>
.box {
width: 80px; height: 80px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white; font-size: 1.5rem;
display: flex; align-items: center; justify-content: center;
margin: 10px; border-radius: 12px;
cursor: pointer; transition: transform 0.2s;
float: left; user-select: none;
}
.box:hover { transform: scale(1.05); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
.box:active { transform: scale(0.95); }
#container { overflow: hidden; padding: 20px; }
.hint { clear: both; color: #666; margin: 20px; font-size: 0.9rem; }
</style>
</head>
<body>
<div id="container">
<div class="box">A</div>
<div class="box">B</div>
<div class="box">C</div>
<div class="box">D</div>
<div class="box">E</div>
<div class="box">F</div>
</div>
<p class="hint">點擊任意方塊隱藏,動態新增的也生效</p>
<button id="addBtn">新增方塊</button>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
// 1. 事件委託:父容器代理所有 .box 的點擊
$('#container').on('click', '.box', function() {
$(this).fadeOut(500, function() {
$(this).remove(); // 動畫完成後從 DOM 移除
});
});
// 2. 動態新增測試
$('#addBtn').click(() => {
const letters = 'GHIJKLMNOPQRSTUVWXYZ';
const random = letters[Math.floor(Math.random() * letters.length)];
$(''+random+'').appendTo('#container').hide().fadeIn(300);
});
</script>
</body>
</html>
// 語法:$(父容器).on(事件, 子選擇器, 處理函數)
$('#container').on('click', '.box', handler);
.box 自動生效,無需重新綁定$(this) 上下文處理函數中 this 指向觸發事件的具體子元素(即匹配 .box 的那個 div),而非 #container。
$(this).fadeOut(500, function() {
$(this).remove(); // 動畫完成後執行
});
hide(1000) / fadeOut(500) 都是動畫方法,返回 jQuery 對象支持鏈式調用document.getElementById('container').addEventListener('click', e => {
const box = e.target.closest('.box');
if (box && box.parentElement === e.currentTarget) {
box.style.transition = 'opacity 0.5s';
box.style.opacity = '0';
setTimeout(() => box.remove(), 500);
}
});
| 需求 | 實現關鍵 |
|---|---|
| 點擊其他地方關閉 | $(document).on('click', e => { if(!$(e.target).closest('.box').length) $('.box').fadeOut(); }) |
| 右鍵菜單操作 | on('contextmenu', '.box', e => { e.preventDefault(); showMenu(e); }) |
| 雙擊編輯 | on('dblclick', '.box', function(){ $(this).html('').find('input').focus(); }) |
| 撤銷隱藏 | 維護堆疊 const removed = []; removed.push({el, html}); 提供恢復按鈕 |
事件委託 + $(this) + 動畫回調 是 jQuery 處理列表類交互的黃金模式。理解冒泡機制、上下文綁定、動畫隊列,能寫出極簡且高性能的交互代碼。現代項目中,同樣邏輯用原生 addEventListener + closest() 可完全替代 jQuery,減少依賴體積。