jfr*_*d00 28
.on()现在提供了一种统一的方法.live(),.delegate()并且.bind()一体化.您可以通过如何使用参数来获取这三者中的任何一个的行为.on().
这些对在功能上是相同的:
// events bound directly to the object they occur on
$('.button').on('click', fn);
$('.button').bind('click', fn);
// events intercepted after bubbling up to a common parent object
$('.container').on("click", '.button', fn);
$('.container').delegate('.button', "click", fn);
Run Code Online (Sandbox Code Playgroud)
更多信息在jQuery博客条目中描述.
在统一这些单独的函数之前,jQuery有多个不同的实现.现在,.on()是超集函数.bind(),.live()并且.delegate()只是调用.on()它们的实现,所以现在只有一个实际事件处理的实现.因此,从这个角度来看,它也是一个代码清理和简化问题.同样,.die(),.undelegate()和.unbind()刚才打电话.off()现在,而不是有独立的实现.
注意:.live()已经弃用了所有版本的jQuery,因为它只是拦截文档对象上所有冒泡事件的特殊情况,因此它可以很容易地被替换为.delegate()或者.on()当文档对象上处理大量事件时,它可能会成为一个性能问题,检查每个事件的很多选择器.将像这样的委托事件挂钩到更接近事件发生位置的公共父级,而不是将它们全部放在文档对象上(因此为什么.live()不好用)会更有效.
从jQuery 1.7源代码,您可以看到所有这些函数现在如何调用,.on()并且.off():
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5397 次 |
| 最近记录: |