将事件添加到附加的ajax内容

pgu*_*rio 4 javascript ajax jquery

假设我有一些链接,我想添加一个javascript动作:

<a class='test'>
<a class='test'>
<a class='test'>
Run Code Online (Sandbox Code Playgroud)

当我的页面加载时,我给他们所有的点击事件:

$('.test').click(function(){
  alert("I've been clicked!")
});
Run Code Online (Sandbox Code Playgroud)

但是让我们说后来我添加了另一个元素,我想给它同样的事件.我不能这样做:

$('.test').click(function(){
  alert("I've been clicked!")
});
Run Code Online (Sandbox Code Playgroud)

因为那时前三个将有2个事件.处理这个问题的最佳方法是什么?

Pra*_*Nag 7

您可以将$ .on绑定到将始终存在于dom中的父元素.

$(document).on('click','.test', function() {
            console.log('Test clicked');
        });
Run Code Online (Sandbox Code Playgroud)

请注意: 您可以替换documentdom中始终存在的元素的任何父元素,父元素越接近越好.

简单事件绑定click不会起作用,click将事件处理程序绑定到绑定时已存在于dom中的元素.因此,它不适用于稍后通过Ajax或jQuery动态添加到dom的元素.为此,你必须使用event delegation.你可以用它$.on来实现这个目的.

检查$ .on的文档

你可以使用$.live但是$ live是折旧的.请改用$ .on.$ .on的等价语法为$ .live和$ .delegate执行相同的操作

$(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+
Run Code Online (Sandbox Code Playgroud)

在这种情况下,事件处理程序将被绑定document.在这个案例test类中,事件将被jQuery委托给target元素.

UPDATE

我建议你$.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 );
} 
Run Code Online (Sandbox Code Playgroud)

对于这些方便的事件处理程序也是如此

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
Run Code Online (Sandbox Code Playgroud)

您可以看到所有方法都在使用$.on$.off自己.所以使用$.on你至少可以保存一个函数调用,虽然在大多数情况下这并不重要.