Js block event append specific implementation
- 2020-03-30 04:07:00
- OfStack
Sometimes you can use e.toppropagation (); E.p reventDefault (); To prevent event bubbling and default event execution. But you cannot prevent the append of events.
When do you want to prevent appends of events?
Such as:
Click "checkout", when such operation, the checkout itself has its own event, but before checkout to determine whether to log in.
We might write:
Js code
if(isLogin){ //Determine whether to log in
console.log(" Not logged in ")
}else{
//Checkout-related code
}
If you click "my home page" there is also login judgment
Login judgment code
if(isLogin){ //Determine whether to log in
console.log(" Not logged in ")
}else{
//Personal center
}
If there are more login judgments. Will there be more code like this? I later found the method stopImmediatePropagation(), which prevents the event from being appended. The above problem is not a problem.
Important:. Ensure that the login judgment event is the first bound event.
The Demo code
<!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="#" class="bill isLogin"> The invoicing </a>
<ul>
<li class="a1 isLogin"> Add to favorites </li>
<li class="a2 isLogin"> Others pay </li>
<li class="a3"> Join car purchase </li>
<li class="a4 isLogin"> My home page </li>
</ul>
<script>
//Bind
first
$(".isLogin").on("click", function (e) {
if(true){ //Login determines
alert(" Not logged in ");
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 login judgment ");
});
</script>
</body>
</html>
In fact, jquery gives us a way to view the event, $._data($('.islogin ').get(0)), open firebug, and type in the console.
Js code
$. _data while forming ($(' isLogin '). The get (0))
You will see the following:
Js code
The Object {events = {... }}, handle = function ()
Click to see an array of events to see what events are bound to the element.