您可以将$ .on绑定到这样的dom中始终存在的父元素。
$(document).on('click','.test', function() { console.log('Test clicked'); });请注意: 您可以用
documentdom中将始终存在的元素的任何父级替换,并且父级越近越好。
具有事件的简单事件绑定
click无法
click将事件处理程序绑定到绑定时dom中已经存在的元素。因此,它不适用于以后通过Ajax或jQuery动态添加到dom中的元素。为此,您必须使用
eventdelegation。您可以
$.on为此目的使用。
检查$ .on的文档
您可以使用,
$.live但是$ live被折旧了。使用$ .on代替。$ .live和$ .delegate的$ .on等效语法,其作用相同
$(selector).live(events, data, handler); // jQuery 1.3+$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+$(document).on(events, selector, data, handler); // jQuery 1.7+
在这种情况下,事件处理程序将绑定到
document。在这种情况下,事件将由jQuery委托给目标元素
test。
更新
我建议您将其
$.on用于所有事件处理,因为所有其他方法都是通过方法
$.on和内部
$.off方法进行路由的。
从jQuery源v.1.7.2中检查这些函数的定义
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 );}这些便捷的事件处理程序也是如此
blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu
您可以看到所有正在使用的方法
$.on及其
$.off自身。因此,使用
$.on它至少可以保存一个函数调用,尽管在大多数情况下这并不重要。



