这篇文章将为大家详细讲解有关jquery解除事件绑定的方法,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
解除事件绑定的方法:1、使用unbind()和undelegate()方法,分别用于解除由bind()和delegate()方法所绑定的事件;2、使用off()方法,可以解除由on()、bind()和delegate()方法所绑定的事件。
解除事件绑定
在元素绑定事件之后,当在某个时刻不再需要该事件处理时,可以解除所绑定的事件。在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.7.js"> </script>
<style type="text/css">
p{width:200px;height:200px;border:1px solid #666;}
#leftp{float:left; margin:0 auto;}
#rightp{float:right;}
</style>
</head>
<body>
<p id="leftp">
<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"/>
</p>
<p id="rightp">右侧展示区</p>
<script type="text/javascript">
$(function(){
//使用bind()方法绑定事件
$("#manyBindBtn").bind({
click:function(){$("#rightp").slideToggle();},
mouseover:function(){$("#rightp").css("background-color","red");},
mouseout:function(){$("#rightp").css("background-color","yellow");}
});
//使用delegate()方法绑定事件
$(document).delegate("#delegateBindBtn","click",function(){
$("#rightp").slideToggle();
});
//使用hover()方法绑定事件
$("#rightp").hover(function(){
$(this).css("background-color","gray");
},function(){
$(this).css("background-color","white");
});
//使用on()方法绑定事件
$("#leftp").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事件绑定
$("#leftp").off("click","#bindBtn");
//8.使用off()方法解除所有按钮上的所有事件绑定
$("input[type=button]").off();
});
});
</script>
</body></html>
关于jquery解除事件绑定的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。