Sometimes you can use e.stopPropagation(); e.preventDefault(); to prevent events from bubbled and execution of default events. But the addition of events cannot be prevented.
Under what circumstances should we prevent the addition of events?
for example:
Click "Checkout". When you operate this, the checkout itself has its own events, but you must determine whether to log in before checking out.
We might write this:
Js code
The code copy is as follows:
if(isLogin){ //Judge whether to log in
console.log("No login")
}else{
//Checkout related code
}
If you click "My Homepage" you will also have a login judgment
Login judgment code
if(isLogin){ //Judge whether to log in
console.log("No login")
}else{
//Personal Center
}
If there are more login judgments. Will there be more codes like the ones above? Later I found out that the stopImmediatePropagation() method prevents event appending. The above question is not a problem.
Important: Make sure that login determines that the event is the first bound event.
Demo Code
The code copy is as follows:
<!DOCTYPE html>
<html>
<head lang="en">
<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="#">Checkout</a>
<ul>
<li>Add to favorites</li>
<li>Others pay</li>
<li>Add to buy a car</li>
<li>My Home Page</li>
</ul>
<script>
//Bind first
$(".isLogin").on("click", function (e) {
if(true){ //Login judgment
alert("No login");
e.stopImmediatePropagation();
}
return false;
});
$(".bill").on("click",function(){
alert("Checkout related content!");
});
$(".a1").on("click",function(){
alert("a1");
});
$(".a2").on("click",function(){
alert("a2");
});
$(".a3").on("click",function(){
alert("Added to cart");
});
$(".a4").on("click",function(){
alert("There is a login judgment");
});
</script>
</body>
</html>
In fact, jquery provides us with a method to view events $._data($('.isLogin').get(0)), open firebug, and enter it in the console.
Js code
$._data($('.isLogin').get(0))
You will see the following:
Js code
Object { events={...}, handle=function()}
Click to see the event array to facilitate viewing what kind of events are bound to the element.