手记

jQuery事件重复绑定解决方案

 今天在使用jQuery过程中碰到了这个隐藏在代码中的问题:事件绑定会累加而不会覆盖掉前者。特此记录下解决方案。

测试代码:

<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!--[if lt IE 9]>     <script src="js/html5shiv.js"></script> <![endif]--> <script src="js/jquery-1.7.2.min.js"></script>    <script>     var test = function(){         $("p").on("click",function(){             //alert($(this).text());             console.log($(this).text());         });          }          var ok = function(){         $("p").off().on("click",function(){             //alert($(this).text());             console.log($(this).text());         });      }          $(document).ready(function(){         $("a").click(test);         $("button").click(test);         $("input").click(ok);     });       </script>   </head> <body>     <a href="#">第一次</a> <button>第二次</button> <input type="button" value="最终" />     <p>0</p>     <p>1</p>     <p>2</p>     <p>3</p>     <p>4</p>     <p>5</p> </body>      </body> </html> 看出问题来了吗?没看出来那就先后点击按钮对数字进行事件绑定,然后再点数字看下效果就知道了。jQuery事件绑定是会累加的,最终那个才是正确写法,绑定前先释放掉。 注:.on及.off在jQuery1.7+支持!

 

0人推荐
随时随地看视频
慕课网APP