on(),bind(),live()用法的区别
以上三种函数都可以为一个页面元素绑定事件,其中on()
是核心,其他两个用法上略有不同。
下面贴上bind()
,live()
的代码
jQuery.fn.extend({
...
bind: function( types, data, fn ) {
return this.on( types, null, data, fn ); //第二个参数为null
},
...
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
//第二个参数为选择器所选中的jq元素
return this;
},
...
});
可以看出,bind()
,live()
都是调用的on()
函数,只不过是传递的参数不同。
体现在用法上的区别如下:
$('#id').bind('click',function(){});
$('#id').bind('click','div',function(){});
//以上两种方法都把事件绑定到$('#id')上,因为bind()方法把‘div’设为null