This article mainly introduces jQuery's method of canceling specific click events, and analyzes the related techniques of jQuery to simply implement event binding and cancel event binding in the form of examples. Friends in need can refer to it
As we all know, jQuery can bind the same event multiple times, and each bound event can be executed. Here comes the problem. In the dynamically generated DOM, we bind two different clicks (assumed to be A and B) for a certain element. When appending the element, all elements are bound to B again... This will lead to the final When clicked, the B event will double up.
Fortunately, jQuery provides us with a very elegant way to cancel clicks under a specific namespace.
<!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>
For more related tutorials, please visit JavaScript video tutorial