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綁定,而且把事件委託交給父元素.