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

相关文章
相关标签/搜索