jQuery--解除事件绑定

解除事件绑定

在元素绑定事件之后,当在某个时刻不再需要该事件处理时,可以解除所绑定的事件。在jQuery中提供了unbind()和undelegate()方法,分别用于解除由bind()和delegate()方法所绑定的事件,通过参数指明需要解除的绑定事件即可。当方法没有提供参数时,表示解除该元素所有的事件绑定。

在jQuery1.7+中提供了off()方法,用于解除由on()、bind()和delegate()方法所绑定的事件。off()方法与on完全相同。

示例:解除事件绑定

<!doctype html>
<html>
  <head>
	<meta charset="utf-8">
	<title>jQuery基本操作事件绑定</title>
	<script type="text/javascript" src="js/jquery-1.x.js"> </script>
   	<style type="text/css">
		div{width:200px;height:200px;border:1px solid #666;}
		#leftDiv{float:left; margin:0 auto;}
		#rightDiv{float:right;}
	</style>
  </head>
  <body>
  	<div id="leftDiv">
    	<input type="button" value="bind事件绑定" id="bindBtn"/>
        <input type="button" value="多事件绑定" id="manyBindBtn"/>
        <input type="button" value="delegate事件绑定" id="delegateBindBtn"/>
        <input type="button" value="解除事件绑定" id="removeBindBtn"/>
    </div>
    <div id="rightDiv">右侧展示区</div>
	<script type="text/javascript">
		$(function(){
			//使用bind()方法绑定事件
			$("#manyBindBtn").bind({
				click:function(){$("#rightDiv").slideToggle();},
				mouseover:function(){$("#rightDiv").css("background-color","red");},
				mouseout:function(){$("#rightDiv").css("background-color","yellow");}
			});
			//使用delegate()方法绑定事件
			$(document).delegate("#delegateBindBtn","click",function(){
				$("#rightDiv").slideToggle();
			});
			//使用hover()方法绑定事件
			$("#rightDiv").hover(function(){
				$(this).css("background-color","gray");
			},function(){
				$(this).css("background-color","white");
			});
			//使用on()方法绑定事件
			$("#leftDiv").on("click","#bindBtn", function(){
				alert("使用bind()方法绑定事件处理");
			});
			//解除事件绑定
			$("#removeBindBtn").on("click",function(){
				//1.使用unbind()解除click事件绑定
				//$("#manyBindBtn").unbind("click");
				//2.使用unbind()解除该元素上的所有事件绑定
				//$("#manyBindBtn").unbind();
				//3.使用off()方法解除bind()方法的click事件绑定
				$("#manyBindBtn").off("click");
				//$(document).off("click","#manyBindBtn");
				//4.使用off()方法解除该元素上的所有事件绑
				//$("#manyBindBtn").off();				
				//5.使用undelegate()方法解除delegate()方法绑定事件
				//$(document).undelegate("#delegateBindBtn","click");
				//6.使用off()方法解除delegate()方法绑定事件
				$(document).off("click","#delegateBindBtn");
				//7.使用off()方法解除on()方法的click事件绑定
				$("#leftDiv").off("click","#bindBtn");
				//8.使用off()方法解除所有按钮上的所有事件绑定
				$("input[type=button]").off();
			});
		});
	</script>
  </body>
</html>

在这里插入图片描述

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值