DIV CSS 佈局教程網

JS 事件綁定:前綁定與後綁定的差別
編輯:關於JavaScript     

這篇文章說明什麼是前綁定與後綁定,並比較幾種常見寫法。

顧名思義:前綁定是元素還沒出生就先綁好某些事件,讓這一類元素一誕生就具備該行為;後綁定則是元素存在之後才去綁。這兩者在實作「動態新增的內容也要有互動」時差別明顯。

頁面元素

<div id="main">
  <a href="#">aaaaaaaaaaaaaaaaaaaaaa</a><br />
  <a href="#">bbbbbbbbbbbbbbbbbbbb</a><br />
  <a href="#">ccccccccccccccccccccccccc</a><br />
  <a href="#">dddddddddddddddddddd</a><br />
  <a href="#">eeeeeeeeeeeeeeeeeeeeee</a><br />
  <a href="#">fffffffffffffffffffffffffffffffff</a><br />
  <a href="#">gggggggggggggggggggg</a><br />
  <a href="#">hhhhhhhhhhhhhhhhhhhh</a>
</div>
<input type="button" value="建立 a 標籤" id="btnCreate" />

JavaScript 部分

<script src="jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {

  // ---- 以下皆為「後綁定」:動態建立出來的元素不會擁有這些事件 ----

  // 寫法 1:後綁定
  // $("#main > a").click(function () {
  //   alert($(this).html());
  // });

  // 寫法 2:後綁定,用 bind 指定事件名
  // $("#main > a").bind("click", function () {
  //   alert($(this).text());
  // });

  // 寫法 3:後綁定,一次綁多個事件
  // $("#main > a").bind({
  //   click:     function () { alert($(this).text()); },
  //   mouseover: function () { $(this).css("background-color", "red") },
  //   mouseout:  function () { $(this).css("background-color", "white") }
  // });

  // 動態建立元素
  $("#btnCreate").bind({
    click: function () {
      $("<br /><a href='#'>我是動態建立的</a>").appendTo("#main");
    }
  });

  // ---- 以下為「前綁定」:動態建立的元素也擁有點擊事件 ----

  // 寫法 4:前綁定,delegate 綁在父元素 #main 上
  // $("#main").delegate("a", "click", function () {
  //   alert($(this).text());
  // });

  // 寫法 5:前綁定,live 的事件源頭是 document
  // 因為 delegate 的源頭是具體要綁定的元素,效率比 live 好得多
  $("#main a").live("click", function () {
    alert($(this).text());
  });

});
</script>

差別在哪裡

前三種寫法都是在 DOM 就緒的那一刻,把事件直接掛到當時存在的那些 a 元素上。之後用按鈕動態 append 進來的新 a,完全不受影響——點了沒反應。

delegate 與 live 則不同,它們利用事件泡泡(event bubbling)的原理,把監聽器掛在父元素或 document 上。新元素被點擊時,事件照樣會往上冒,於是被攔下來處理。這就是「前綁定」的效果。

至於 delegate 與 live 的效能差異:live 一律掛在 document 上,任何頁面的點擊都要經過它判斷一次;delegate 掛在指定的容器上,判斷範圍小得多。所以 delegate 明顯較快。

今日寫法

live 已在 jQuery 1.9 中移除,delegate 也在 jQuery 3.0 中被標記為 deprecated。現在的標準寫法是 on:

// 後綁定:直接綁在元素上
$("#main > a").on("click", function () { alert($(this).text()); });

// 前綁定(事件委派):delegation 寫法
$("#main").on("click", "a", function () { alert($(this).text()); });

用 on 就能同時取代 bind、delegate 與 live 三種舊寫法,不必再記哪個方法對應哪種情境。

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