DIV CSS 佈局教程網

jQuery 的 on() 綁定動態元素時,最容易踩的四個坑
編輯:JQuery入門技巧     

自 jQuery 1.7 起,舊的 bind()、live()、delegate() 都被 on() 整合取代。但許多人換用 on() 之後,還是會遇到「事件怎麼觸發不了」的狀況。以下用點擊事件為例,把四種情況逐一驗證。

一、監聽事件「之前」就存在的 DOM:正常觸發

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#test {
    height: 100px; font-size: 50px; color: yellow;
    line-height: 100px; background-color: red; text-align: center;
}
</style>
<script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script>
$(function () {
    var oDiv = $('<div id="test">點我</div>');
    $(document.body).append(oDiv);

    $("#test").on('click', function () {
        alert('這是事件前添加的 DOM,可以正常觸發點擊事件');
    });
});
</script>
</head>
<body>
<div id="wrap"></div>
</body>
</html>

二、監聽事件「之後」才產生的 DOM:無法觸發

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#test {
    height: 100px; font-size: 50px; color: yellow;
    line-height: 100px; background-color: red; text-align: center;
}
</style>
<script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script>
$(function () {
    $("#test").on('click', function () {
        alert('這是事件後添加的 DOM,無法正常觸發點擊事件');
    });

    var oDiv = $('<div id="test">點我</div>');
    $(document.body).append(oDiv);
});
</script>
</head>
<body>
<div id="wrap"></div>
</body>
</html>

三、解法:事件委託,但委託目標必須先存在

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#test {
    height: 100px; font-size: 50px; color: yellow;
    line-height: 100px; background-color: red; text-align: center;
}
</style>
<script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script>
$(function () {
    var oWrap = $('<div id="wrap"></div>');
    $(document.body).append(oWrap);

    // 把事件綁在已存在的 #wrap 上,由它代收 #test 的點擊
    $("#wrap").on('click', $('#test'), function () {
        alert('委託對象在事件前添加,可以正常觸發點擊事件');
    });

    var oDiv = $('<div id="test">點我</div>');
    $("#wrap").append(oDiv);
});
</script>
</head>
<body>
</body>
</html>

四、委託對象在事件之後才加入:依然失效

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#test {
    height: 100px; font-size: 50px; color: yellow;
    line-height: 100px; background-color: red; text-align: center;
}
</style>
<script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script>
$(function () {
    $("#wrap").on('click', $('#test'), function () {
        alert('委託對象在事件後添加,無法正常觸發點擊事件');
    });

    var oWrap = $('<div id="wrap"></div>');
    $(document.body).append(oWrap);

    var oDiv = $('<div id="test">點我</div>');
    $("#wrap").append(oDiv);
});
</script>
</head>
<body>
</body>
</html>

問題的根源,以及更該用的寫法

上面第三、第四個例子其實藏著一個寫法上的錯誤:$("#wrap").on('click', $('#test'), ...) 的第二個參數被傳入了「一個 jQuery 物件」。on() 的第二參數應該是選擇器字串,正確寫法是 $("#wrap").on('click', '#test', function () {...})。傳物件進去時,jQuery 無法把它當成委託目標比對,行為自然不如預期。

更根本的觀念是:on() 直接綁定的形式($(selector).on('click', fn))只在綁定那一刻對「已存在的元素」生效;而事件委託形式($(document).on('click', selector, fn))是把手機式的事件監聽掛在祖先元素上,靠事件泡泡(event bubbling)在點擊發生時判斷 event.target 是否符合選擇器,因此後來才加入的後代元素也能被涵蓋。這正是處理動態內容的標準做法。

實務建議:委託的祖先盡量選靠近內容、位置穩定的容器(例如 tbody 或列表外層),不要一律掛在 document 上,否則全站點擊都要跑一次選擇器比對,效能會受影響。

以上就是這次的整理,希望對你的事件處理有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved