jquery 绑定事件的方式?
- 其实大体可以分为能不能绑定动态加载出来的节点事件来分类
1.直接在标签上绑定
<button onclick='btn()'></button>
2. 事件名绑定
<button id='btn'></button>
<script>
$("#btn").click(function(){
console.log();
})
</script>
3. bind()绑定,与直接事件绑定类似(无法动态绑定,)
源码:
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
}
4. live,on动态绑定
jquery 1.7版本以前使用live 动态绑定
jquery 1.7版本以后使用on 动态绑定
5.live,delegate,on动态绑定
先看这三者的源码:
live:
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
}
delegate:
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
}
on:
on(type,[selector],[data],fn)
- 首先是Live:
绑定的是this.context,
$('#myol li').context; //document
$('#myol li','#myol').context; //document
大多数情况下this.context 绑定的document,
故可推断事件的委托交给了doucment。
- 然后就是delegate,
$("#btn").delegate('li','click',function(){})
相当于返回的时候调用了一次on
- 最后介绍on ,
on 经过测试,事件委托并不是交给document,而是绑定到父元素上,如果不绑定到父元素上的时候,事件绑定会失效。
$('#father').on('click','#son',function(){})
— 请大家谨慎使用,最好使用on绑定,而且把事件委托交给父元素.