Home > Article > Web Front-end > The specific implementation method of preventing event appending in js
You can use e.stopPropagation(); e.preventDefault(); to prevent events from bubbling and the execution of default events. But it cannot prevent the addition of events. If you want to add, please see the implementation method below
Sometimes you can use e.stopPropagation(); e.preventDefault(); to prevent event bubbling and the execution of default events. . But it cannot prevent the event from being added.
Under what circumstances should we prevent the addition of events?
For example:
Click "Checkout". When doing this, the checkout itself has its own event, but you need to determine whether to log in before checking out.
We may write like this:
Js code
The code is as follows:
if(isLogin){ //判断是否登录 console.log("没有登录") }else{ //结账相关代码 } 如果点击“我的主页”也有登录判断 登录判断代码 if(isLogin){ //判断是否登录 console.log("没有登录") }else{ //个人中心 }
If there are more login judgments. Will there be more code like the above? Later I discovered the stopImmediatePropagation() method to prevent events from being appended. The above problem is no longer a problem.
Important: Make sure that the login judgment event is the first bound event.
Demo code
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>demo</title> <script src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script> </head> <body> <a href="#" class="bill isLogin">结账 </a> <ul> <li class="a1 isLogin">加入收藏夹</li> <li class="a2 isLogin">他人支付</li> <li>加入购入车</li> <li class="a4 isLogin">我的主页</li> </ul> <script> //最先绑定 $(".isLogin").on("click", function (e) { if(true){ //登录判断 alert("没有登录"); e.stopImmediatePropagation(); } return false; }); $(".bill").on("click",function(){ alert("结账相关内容!"); }); $(".a1").on("click",function(){ alert("a1"); }); $(".a2").on("click",function(){ alert("a2"); }); $(".a3").on("click",function(){ alert("已加入购物车"); }); $(".a4").on("click",function(){ alert("有登录判断"); }); </script> </body> </html>
In fact, jquery provides us with a method to view events $._data($('.isLogin'). get(0)), open firebug, and enter in the console.
Js Code
$._data($('.isLogin').get(0))
You will see the following:
Js Code
Object { events={...}, handle=function()}
Click to see the eventarray, which is convenient for viewing the binding on the element What kind of event happened.
The above is the detailed content of The specific implementation method of preventing event appending in js. For more information, please follow other related articles on the PHP Chinese website!