on方法格式:on(events,[selector],[data],fn)
off方法格式:如 off()、 off(“click”)、 off(“click.abc”)、 off(“.abc”)、 off(“click”,fn),用于替代unbind()和die()和undelegate()
除了之前学过的bind和unbind用来绑定事件,jQuery中还提供了live和die以及delegate和undelegate这两组函数用来处理事件委托,所谓事件委托就是把匹配元素的事件冒泡给document,每当有新元素时jquery帮你判断事件type和触发事件的target,如果这两项都匹配,那么就把该事件类型由document委托给新增加的元素。这样就有三组事件处理函数了,太混乱了,推出on和off来解决。
下面的这个关于on方法处理jquery事件的例子比较了on与bind与delegate以及live的区别,主要功能:
替代bind()函数
替代bind()函数并使用事件对象接收传递的参数
替代bind()函数通过空格绑定多个事件
替代bind()函数以一个对象格式绑定多个事件
替代bind()函数阻止浏览器默认行为并阻止冒泡
替代live()和delegate()进行事件委派
html代码:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>on方法</title>
<style>
</style>
</head>
<body>
<form action="1.html">
<input type="submit">
</form>
<input id="btn1" type="button" value="替代bind()函数">
<input id="btn2" type="button" value="替代bind()函数并使用事件对象接收传递的参数">
<input id="btn3" type="button" value="替代bind()函数通过空格绑定多个事件">
<input id="btn4" type="button" value="替代bind()函数以一个对象格式绑定多个事件">
<div id="box">
<input class="btn5" type="button" value="替代live()和delegate()进行事件委派">
</div>
</body>
</html>
jquery代码:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn1").on("click",function(){
alert("btn1");
});
$("#btn2").on("click",{myname:"zdw"},function(e){
alert("btn2"+e.data.myname);
});
$("#btn3").on("click mouseenter",function(e){
alert("btn3"+e.type);
});
$("#btn4").on({
mouseenter:function(){
alert("这是mouseenter");
},
mouseleave:function(){
alert("mouseleave");
}
});
$("form").on("submit",function(){
alert("替代bind()函数阻止浏览器默认行为并阻止冒泡");
return false;//相当于调用e.preventDefault()
});
//$("#box").on("click",".btn5",function(){
//$(".btn5").live("click",function(){//不需要通过父元素
$("#box").delegate(".btn5","click",function(){//注意和on的顺序不同
$(this).clone().appendTo("#box");//this指的是最终被绑定事件的元素
});
});
</script>
页面效果:
大伙拷贝了代码,点击一下结合注释,就能很好的理解on方法了。