jquery中的.delegate()

来源:互联网 发布:如何做淘宝内部优惠群 编辑:程序博客网 时间:2024/05/29 19:49

原文:http://api.jquery.com/delegate/

参考译文:http://www.css88.com/jqapi-1.9/delegate/


Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

描述: 为所有匹配选择器(selector参数)的元素绑定一个或多个事件处理函数,基于一个指定的根元素的子集,匹配的元素包括那些目前已经匹配到的元素,也包括那些今后可能匹配到的元素。


As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the.on() method. In general, these are the equivalent templates for the two methods:

从jQuery 1.7开始,.delegate()已经被.on()方法取代。但是,对于早期版本,它仍然是使用事件代理(委派)最有效的方式。事件绑定和代理(委派)的更多信息请查看.on()方法。在一般情况下,这些是两种方法的等效的方法:

1
2
3
4
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );

For example, the following .delegate() code:

1
2
3
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});

is equivalent to the following code written using .on():

1
2
3
$( "table" ).on( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});

To remove events attached with delegate(), see the .undelegate() method.

Passing and handling event data works the same way as it does for .on().

要移除使用delegate()绑定的事件,查看.undelegate()方法。

传递和处理事件数据的方式和.on()的方式一样的。

Additional Notes:

  • Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by.delegate() will propagate to the elements to which they are delegated; event handlers bound on any elements below it in the DOM tree will already have been executed by the time the delegated event handler is called. These handlers, therefore, may prevent the delegated handler from triggering by callingevent.stopPropagation() or returningfalse.

Additional Notes:(其他注意事项:)

  • 因为.live()方法处理事件一旦传播到文档的顶部,live事件是不可能停止传播的。同样地,.delegate()处理的事件将冒泡至它的代理元素;同时,任何在 DOM 树中,比这些元素低的元素上绑定的相同事件,在 .delegate() 事件被调用的时候,也会被触发。因此,如果要在事件中阻止委托事件被触发,可以调用event.stopPropagation()或者返回false防止委派处理程序冒泡。




0 0