DIV CSS 佈局教程網

深入淺談 jQuery 的 delegate 與 live 方法
編輯:JavaScript綜合知識     

在 jQuery 中,live 與 delegate 這兩個方法專門用來為「動態產生的 DOM 元素」綁定事件。它們都是 bind 方法的變體,卻能解決 bind 無法處理動態元素的痛點。本文帶你徹底搞懂兩者的用法與差異。

為什麼需要 live 與 delegate?

對於頁面上「固定存在」的 DOM 元素,我們用 bind 綁定事件就足夠了。但如果是透過 Ajax 或 JS 動態產生的元素,bind 就束手無策了——因為綁定事件的當下,那些元素還不存在。這時 live 與 delegate 就能派上用場,透過事件委派機制自動涵蓋未來新增的元素。

live 方法

live 用來為某個(某類)元素綁定事件方法:

// live
$("td").live("click", function () {
  alert($(this).html());
});
// 帶選擇器的寫法也可以
$("#list td").live("click", function () {
  alert($(this).html());
});

delegate 方法

delegate 則是為某個元素的「子元素」綁定事件,也就是把事件委託給子元素處理:

$("#list").delegate("td", "click", function () {
  alert($(this).html());
});

完整 DEMO

以下示範如何透過一個模板動態產生表格列,並用 live 為動態產生的 td 綁定點擊事件:

<html lang="en">
<head>
  <meta charset="utf-8" />
  <script src="jquery.js" type="text/javascript"></script>
  <script id="listTemplate" type="text/html">
    <tr>
      <td>[UserID]</td>
      <td>[UserImg]</td>
      <td>[UserName]</td>
    </tr>
  </script>
  <script type="text/javascript">
    var reg = new RegExp("[([^[]]*?)]", 'igm'); // i g m 分別指定區分大小寫、全局、多行匹配
    $(function () {
      // live 為動態 td 綁定點擊
      $("#list td").live("click", function () {
        alert($(this).html());
      });
      $("#addFun").click(function () {
        var html = document.getElementById("listTemplate").innerHTML;
        var source = html.replace(reg, function (node, key) {
          return { 'UserImg': '1', 'UserName': 'zhang', 'UserID': '1' }[key];
        });
        $("#list").append(source);
      });
    });
  </script>
</head>
<body>
  <input type="button" id="addFun" value="click me" />
  <table id="list" border="1"><tbody></tbody></table>
</body>
</html>

live 與 delegate 的差異

簡單來說,live 是針對「符合選擇器的所有元素」綁定事件,範圍較廣;而 delegate 則是針對「某個元素的指定子元素」進行事件委派,能更精準地控制事件的來源範圍。在需要為動態內容綁定大量事件時,這兩個方法都能大幅簡化你的程式碼。

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