萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 事件委託實戰:點擊隱藏任意元素的極簡模式

核心代碼(3 行)

// 事件委託:綁定在父容器,處理動態新增元素
$('#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>

核心知識點

1. 事件委託

// 語法:$(父容器).on(事件, 子選擇器, 處理函數)
$('#container').on('click', '.box', handler);
  • 利用事件冒泡:子元素事件冒泡到父容器
  • 動態新增的 .box 自動生效,無需重新綁定
  • 性能優:只綁定 1 個監聽器,而非 N 個

2. $(this) 上下文

處理函數中 this 指向觸發事件的具體子元素(即匹配 .box 的那個 div),而非 #container。

3. 動畫隊列與回調

$(this).fadeOut(500, function() {
    $(this).remove(); // 動畫完成後執行
});
  • hide(1000) / fadeOut(500) 都是動畫方法,返回 jQuery 對象支持鏈式調用
  • 回調函數確保 DOM 移除在視覺消失後,避免閃爍

原生 JS 等效實現(無依賴)

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,減少依賴體積。

copyright © 萬盛學電腦網 all rights reserved