jQuery的unbind()函数详解

jQuery绑定事件非常方便,有bindunbind、live、one,还有它帮你把一些常用的事件给单独了出来,比如控件的onclick事件,我们绑定onclick事件的时候只需要

1 $("#testButton").click(function() {
2 alert("I'm Test Button");
3 });

详细的可以参考我写过的jQuery事件机制jquery如何绑定事这两篇文章

如果我们要取消绑定的事件?jQuery有unbind的方法,专门用来取消绑定的事件

1 $("#testButton").unbind("click");

是不是很简单?如果你的click有2个事件的话,你还可以使用unbind("click", fnName)来删除特定函数的绑定。

为什么有这个取消特定函数的方法呢,我们来看下例子,我们会发现,javaScript的事件,跟C#的事件一样,事件的绑定是叠加(+=) 而不是覆盖。

01 var Eat = function() {
02 alert("我要吃饭");
03 }
04 var PayMoney = function() {
05 alert("先付钱");
06 }
07 jQuery(document).ready(function() {
08 $("#testButton").click(Eat);
09 $("#testButton").bind("click", PayMoney);
10 });

我们发现会先弹出:“我要吃饭”紧接着会弹出“先付钱”

要取消绑定特定函数的话:

1 $("#testButton").unbind("click", PayMoney);

注意,jQuery的unbind方法只能取消jquery bind()方法绑定的事件,

在jQuery的源码中我们可以看到$().click最后还是调用了$().bind("click")事件,所以只要是jQuery添加的事件,unbind就能解除事件绑定.对于这种原生JS添加的事件或者其他JS框架添加的事件,unbind就无能为力了

1 <input id="testButton" type="button" value="Test Button" onclick="Eat();" />
2 <script type="text/javascript">
3 jQuery(document).ready(function() {
4 $("#testButton").unbind("click", Eat);
5 $("#testButton").unbind();
6 $("#testButton").bind("click", PayMoney);
7 });
8 </script>

大家猜猜,会显示什么?吃饭?付钱?答案是Eat -> PayMoney,啊!!!我这里取消了绑定,又删除了特定的绑定,为什么还会执行Eat呢?

仔细一看有个

1 onclick="Eat();"

unbind函数如何解决这个问题?大家去看下这篇文章jQuery替换element元素上已经绑定的事

原文地址:https://www.cnblogs.com/aaa6818162/p/2203438.html