这篇文章主要介绍了jquery取消特定的click事件实现方法,结合实例形式分析了jquery简单实现事件绑定及取消事件绑定的相关技巧,需要的朋友可以参考下
众所周知, jquery可以多次绑定同一种事件, 而且绑定的每个事件都可以执行。 问题来了, 在动态生成的dom中, 我们为某一元素绑定了两种不同的click(假设为a、b), append元素时, 所有元素又绑定一次b, …… 这样会导致最后点击时b事件会成倍往上翻。
幸运的是,jquery 为我们提供了很优雅的方式, 来取消特定命名空间下的click.
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en""http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title>无标题页</title> <script src="jquery/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ $("#ptest").click(function(){ alert("正式事件。"); }); }); function bindevent(){ for(var i=0;i<3;i++){ $("#ptest").bind("click.test",function(){ testevent(); }); } } function testevent(){ alert("测试事件"); } function ignoremultievent(){ $("#ptest").unbind("click.test").bind("click.test",function(){ testevent(); }); } </script></head><body> <p id="ptest" style="height: 163px;text-align:center;line-height:163px;width: 500px; background-color: #0000ff;"> 点我进行测试 </p> <input id="button2" type="button" value="为上面的p绑定3次测试事件" onclick="bindevent()" /> <input id="button1" type="button" value="保留正式事件, 取消已绑定的多次测试事件,再绑定一次测试事件 " onclick="ignoremultievent()" /></body></html>
更多相关教程请访问 javascript视频教程