Talk about JavaScript events, event bubbling, event capture, and blocking default events These three topics, whether in the interview or in peacetime work, are difficult to avoid.
1. Event bubbling
let's look at a piece of code:
var $input = document.getelementsbytagname ("input") [0];
var $div = document.getelementsbytagname ("div") [0];
var $body = document.getElementsByTagName ("body") [0];
$input. onclick = function (e) {
This.style.border = "5px solid red"
var e = e | | window.e;
Alert ("Red")
}
$div. onclick = function (e) {
This.style.border = "5px solid green"
alert ("green")
}
$body. onclick = function (e) {
This.style.border = "5px solid yellow"
alert ("Yellow")
}
HTML code
<div>
<input type= "button" value= "test event bubbling"/>
</div> Pop "Red", "green", "yellow" in turn.
Your intention is to trigger the button element, which is triggered along with the event that the parent element binds. This is the event bubbling.
If the event binding to input is changed to:
$input. onclick = function (e) {
This.style.border = "5px solid red"
var e = e | | window.e;
Alert ("Red")
e.stoppropagation ();
}
This time only "red" pops up because the event bubbles are blocked.
2. Event Capture
since there is an event bubbling, there can also be a catch of events, which is a reverse process. The difference is from the top-level element to the target element or from the target element to the top level element.
Look at a piece of code:
$input. AddEventListener ("click", Function () {
This.style.border = "5px solid red";
Alert ("Red")
}, True
$div. AddEventListener ("click", Function () {
This.style.border = 5px Solid Green ";
Alert ("Green")
}, True
$body. AddEventListener ("click", Function () {
This.style.border = 5px Solid Yellow ";
Alert ("Yellow")
}, True)
This time, in turn, pop-up "yellow", "green", "Red", which is the capture of events.
3. Block Default Events
There are some HTML elements default behavior, such as a tag, click a jump action; The submit type input in form form has a default commit jump event; The reset type input has reset form behavior. If you want to block the default behavior of these browsers, JavaScript provides a way for you.
var $a = document.getElementsByTagName ("a") [0];
$a. onclick = function (e) {
alert ("Jump action Blocked by me")
E.preventdefault ();
Return false;//can also
}
<a href= "http://keleyi.com" > Collayi </a> Default event is gone.
Since return false and E.preventdefault () are the same effect, do they differ? Of course.
The default behavior of event hosts can be organized only in HTML event properties and DOM0-level event-handling methods by returning return false.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.