.delegate()

.delegate( selector, eventType, handler ) 官网原E文: jQuery

描述: 为所有选择器匹配的元素附加一个处理一个或多个事件,现在或将来,基于一组特定的根元素。

  • version added: 1.4.2.delegate( selector, eventType, handler )

    selector选择器字符串,用于过滤器触发事件的元素。

    eventType一个包含一个或多个JavaScript事件类型的字符串,比如"click"或"keydown,"或自定义事件的名称。

    handler每当事件触发时执行的函数。

  • version added: 1.4.2.delegate( selector, eventType, eventData, handler )

    selector选择器字符串,用于过滤触发事件的元素。

    eventType一个包含一个或多个JavaScript事件类型的字符串,比如"click"或"keydown,"或自定义事件的名称。

    eventData将要传递给事件处理函数的数据映射。

    handler每当事件触发时执行的函数。

Delegate(委派)是使用.live()方法的另一个选择,允许每个事件绑定到特定的DOM元素。例如,下面的委托的代码:

$("table").delegate("td", "hover", function(){
	$(this).toggleClass("hover");
});

相当于下面使用.live()书写的代码 :

$("table").each(function(){
	$("td", this).live("hover", function(){
		$(this).toggleClass("hover");
	});
});

另见.undelegate() 方法,用于删除通过.delegate()添加的事件。

注意:

  • 自从.live()方法处理事件一旦传播到文档的顶部,live事件是不可能停止传播的。同样地,.delegate() 事件将始终传播给其中包含的被委托元素;元素上的事件将在被委托事件被调用的时候执行。

Examples:

Example: 点击添加另一个段落。请注意, .delegate() 绑定所有段落的click事件 - 甚至是新的段落。

<!DOCTYPE html>
<html>
<head>
  <style>
  p { background:yellow; font-weight:bold; cursor:pointer; 
      padding:5px; }
  p.over { background: #ccc; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Click me!</p>

  <span></span>
<script>
    $("body").delegate("p", "click", function(){
      $(this).after("<p>Another paragraph!</p>");
    });
</script>

</body>
</html>

Demo:

Example: 每当段落的文字被点击时候,要显示一个警告框:

$("body").delegate("p", "click", function(){
  alert( $(this).text() );
});

Example: 返回false,取消默认的行为,防止从它冒出来的,:

$("body").delegate("a", "click", function() { return false; })

Example: 要取消默认动作只有通过使用preventDefault方法。

$("body").delegate("a", "click", function(event){
  event.preventDefault();
});

Example: 也可以绑定自定义事件。

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; }
  span { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
  <p>Has an attached custom event.</p>
  <button>Trigger custom event</button>
  <span style="display:none;"></span>
<script>

    $("body").delegate("p", "myCustomEvent", function(e, myName, myValue){
      $(this).text("Hi there!");
      $("span").stop().css("opacity", 1)
               .text("myName = " + myName)
               .fadeIn(30).fadeOut(1000);
    });
    $("button").click(function () {
      $("p").trigger("myCustomEvent");
    });

</script>

</body>
</html>

Demo:

jQuery 1.6 API 中文版Clove整理、修订