jQuery中的事件綁定的幾種方式

jQuery目前有on(),bind(),delegate(),live()四種綁定方式,可是隨着版本的不斷更新,有的方式也相應的被淘汰掉html

【band()方式綁定】函數

    3.0版本以前的綁定方式比較經常使用的是bind()綁定事件,解除事件的方式是unbind(),可是在3.0以後band()的綁定方式也別相應的解除掉了。bind()的事件綁定是隻對當前頁面選中的元素有效。若是你想對動態建立的元素bind()事件,是沒有辦法達到效果的,以下代碼。this

 1 <body>
 2 <button id="add" type="button">add DIV</button>
 3 <button id="del" type="button">del DIV</button>
 4 <button id="onBtn" type="button">綁定事件</button>
 5 <button id="offBtn" type="button">解綁事件</button>
 6 <div id="container">
 7     <div class='created'>我是原生div<div/>
 8 </div>
 9 </body>
10 <script>
11     $(function () {
12         $("#add").click(function(){
13             $("#container").prepend("<div class='created'>我是動態生成的div<div/>")
14         });
15         $("#del").click(function(){
16             $("div").remove(".created:first")
17         });
18         $("#onBtn").click(function(){
19             $("#container").on("click",".created",function(){
20                 alert(1);
21             });
22         });
23         $("#offBtn").click(function(){
24             $("#container").off("click");
25         })
26     })
27 </script>

delegate(),live()兩種綁定方式並不太經常使用,所以推薦下面這種方式,on()綁定。spa

【on()事件綁定】code

① 使用on進行單事件綁定htm

$("button").on("click",function(){
$(this) 取到當前調用事件函數的對象
console.log($(this).html());
});


 ② 使用on同時爲多個事件,綁定同一函數
$("button").on("mouseover click",function(){
console.log($(this).html())
});

 ③ 調用函數時,傳入自定義參數
$("button").on("click",{name:"jianghao"},function(event){
使用event.data.屬性名 找到傳入的參數
console.log(event.data.name);
})

④ 使用on進行多事件多函數綁定
$("button").on({
click:function(){
console.log("click")
},
mouseover:function(){
console.log("mouseOver")
}
});

⑤ 使用on進行事件委派
 >>> 將本來須要綁定到某元素上的事件,改成綁定在父元素乃至根節點上,而後委派給當前元素生效;
eg:$("p").click(function(){});
 $(document).on("click","p",function(){});
做用:
默認的綁定方式,只能綁定到頁面初始時已有的p元素,當頁面新增p元素時,沒法綁定到新元素上;
使用事件委派方式,當頁面新增元素時,能夠爲全部新元素綁定事件

對象

off() 取消事件綁定
1. $("p").off(): 取消全部事件
2. $("p").off("click"): 取消點擊事件
3. $("p").off("click mouseover"):取消多個事件
4. $(document).off("click","p"):取消事件委派

blog

相關文章
相關標籤/搜索