An introduction to the use of event bubbles for event object e in jQuery

  • 2020-03-30 02:45:05
  • OfStack

I didn't see the concept of event object when I checked the manual before. What I wanted to achieve was to click on a text box and see a drop-down checkbox. When the text box lost focus, I would trigger a blur event to hide the drop-down box. But when I have to select multiple checkboxes it also hides it and I can't choose, which is frustrating. After a day of research, I finally lost focus. I found an event bubbling on the Internet and found that I could achieve this function by clicking.

E.toppropagation () prevents the event from bubbling
 
<head> 
<title></title> 
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script> 
</head> 
<body> 
<table> 
<tr> 
<td><span> Bubble event test </span></td> 
</tr> 
</table> 
</body> 

Let's look at this code first:
 
<script type="text/javascript"> 
$(function () { 
$("table").click(function () { alert("table alert"); }); 
$("td").click(function () { alert("td alert"); }); 
$("span").click(function (){ 
alert("span alert"); 
}); 
}); 
</script> 

We'll see this: span alert -> Td alert - > Table alert. This is called event bubbling. That is, from bottom to top, from inside to outside, the events are triggered in turn. The condition that can be triggered in turn is that there are multiple nested tags with the same event, and the cut events will occur simultaneously, and the response to the same event will be implemented from the inside out.

Sometimes we don't want things to bubble up.
 
<script type="text/javascript"> 
$(function () { 
$("table").click(function () { alert("table alert"); }); 
$("td").click(function () { alert("td alert"); }); 
$("span").click(function (e){ 
alert("span alert"); 
e.stopPropagation(); 
}); 
}); 
</script> 

When I implemented the click event for the entire document, I was able to stop the events from bubbling in the text field and the drop-down marquee, so that clicking on them again would not cause the document to trigger the event.

If you want information about the event, you add an e object to the knowledge method, which is the event object.

E.p. ventdefault () prevents event default behavior.
 
$("a").click(function (e) { 
alert(" The default behavior is disabled "); 
e.preventDefault(); 
}); 
<a href="http://www.baidu.com"> test </a> 

Return false is equivalent to calling both e.venture default () and e.toppropagation ()

In addition to blocking the default behavior, return false also prevents the event from bubbling. If you have a copy of the jquery source code, check out the following:
 
if (ret===false){ 
  event.preventDefault(); 
  event.stopPropagation(); 
} 

Related articles: