在jQuery中,有四種綁定事件方法。分別是:on,live,bind,delegate
他們相對(duì)應(yīng)的事件移出方法為:off,die,unbind,undelegate
1.bind
bind(type,[data],function(){});
type :事件類型
data:傳入監(jiān)聽函數(shù)的參數(shù)
function:監(jiān)聽函數(shù),可傳event對(duì)象,但這里event不是原生js的,是jQuery封裝過的
bind是在選擇到的元素(目標(biāo)元素)上綁定事件類型的監(jiān)聽函數(shù),動(dòng)態(tài)添加元素需再bind
源碼:
bind:function(types,data,fn){
return this.on(types,null,data,fn);
}
2.live
live(type,[data],fn)
參數(shù)與bind一致
區(qū)別:Iive將事件綁定到this.context,而不是自己身上
源碼:
live:function(types,data,fn){
jQuery(this.context).on(types,this.selector,data,fn)
return this;
}
context:元素限定范圍(通常document)
主要是利用事件委托機(jī)制,把元素綁定到document上
3.由于live中時(shí)間委托機(jī)制范圍太大為document,所以delegate為解決此問題產(chǎn)生
deletage相對(duì)于live多了個(gè)參數(shù)selector,用來(lái)指定觸發(fā)事件的目標(biāo)元素
監(jiān)聽器綁定事件到調(diào)用此方法的元素上
delegate:function(selector,types,data,fn){
return this.on(types,selector,data,fn)
}
4.on :根據(jù)前面幾個(gè)例子你會(huì)發(fā)現(xiàn),在每個(gè)方法中都有調(diào)用on
on(type,[selector],[data],fn);
于deletage 相似,但參數(shù)順序不用,而且selector變?yōu)榭蛇x項(xiàng),靈活性更強(qiáng),也是jQuery推薦寫法