jQuery中 的绑定机制(bind live delegate on)

Posted by VickyWu on August 24, 2016
  • .bind( type [, data ], handler ) type:事件类型,如click、change、mouseover等; data:传入监听函数的参数,通过event.data取到。可选; handler:监听函数,可传入event对象,这里的event是jQuery封装的event对象,与原生的event对象有区别,使用时需要注意。 我们来瞄一眼bind的源码:
    bind: function( types, data, fn ) {
    return this.on( types, null, data, fn );
    }
    

    可以看到内部是调用了on方法。bind的特点就是会把监听器绑定到目标元素上,但对于动态添加的元素,不会绑定事件。必须再bind一次。

我们来看一个例子:

$( "#foo" ).bind( "click", function() {
  alert( "User clicked on 'foo.'" );
});

jQuery还有一种事件绑定的简写方式如a.click(function(){});、a.change(function(){});等,它们的作用与bind一样,仅仅是简写而已。

  • live(type [,data], fn) live的参数和bind一样,上源码:
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}

可以看到live方法并没有将监听器绑定到自己(this)身上,而是绑定到了this.context上了。这个context是什么东西呢?其实就是元素的限定范围,通常可以认为这个context就是document了,即live方法把监听器绑定到了document上了。因为将监听器绑定到了document上,所以事件的处理得等待层层冒泡,直到冒泡到根节点才开始处理,根节点的负担太重了。为此,jQuery官方已宣布在1.7版本开始废弃live,改用其他方式代替。所以,大家就不用看例子了。。。

  • .delegate( selector, type, data, handler )

参数多了一个selector,用来指定触发事件的目标元素,监听器将被绑定在调用此方法的元素上。看看源码:

delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
}

可以看出该方法又是调用了on,并且把selector传给了on。对于动态添加的元素,会绑定事件。 看看示例:

$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});
  • .on( type [, selector ] [, data ], handler ) 参数与delegate差不多,但还是有细微的差别,首先type与selector换位置了,其次selector变为了可选项。
$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

如果用的jQuery版本是1.7+的话,建议使用.on()方法绑定事件。jQuery源码中.bind()、.delegate()方法都是通过.on()方法实现的。直接调用on方法会提高性能