以上三种函数均可觉得一个页面元素绑定事件,其中on()
是核心,其余两个用法上略有不一样。css
下面贴上bind()
,live()
的代码jquery
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()
函数,只不过是传递的参数不一样。dom
体如今用法上的区别以下:函数
$('#id').bind('click',function(){}); $('#id').bind('click','div',function(){}); //以上两种方法都把事件绑定到$('#id')上,由于bind()方法把‘div’设为null $('#id').live('click',function(){}); $('#id').live('click','div',function(){}); //第二种方法能够将事件绑定到$('#id div')中
on()
函数代码解析on: function( types, selector, data, fn, /*INTERNAL*/ one ) { ....//判断参数类型,肯定相应参数 return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); } jQuery.event = { add: function( elem, types, handler, data, selector ) { .... if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } .... } .... }
原理从代码中能够看出,其实仍是调用原生JavaScript
中的绑定事件接口。值得一提的是,在为页面中的元素组进行绑定事件的时候,要考虑使用事件代理的方法对代码进行优化。例子以下:优化
$('#myTable td').on('click',function(){ $(this).css('background','red'); }); //给每个td元素都绑定事件 $('#myTable').on('click',function(e){ var $clicked = $(e.target); //e.target能够捕捉到触发事件的目标 $clicked.css('background','red'); }); //这种使用事件代理的方法只需向父元素绑定一个事件 $('#myTable td').on('click','td',function(){ $(this).css('background','red'); }); //jquery中的on()方法将这种事件监听封装起来。
关于事件对象event的事件目标属性,在dom中这个属性名是
target
,在IE对象中这个属性名是srcElement
.this