When talking about JavaScript events, it is difficult to avoid three topics: event bubbles, event capture, and blocking default events, whether it is interview or in daily work.
1. Event bubbles
Let’s take a 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 bubbles" /></div> "red","green","yellow" pops up in turn.
Your original intention is to trigger the button element, but it is triggered together with the event bound to the parent element. This is the event bubble.
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();}At this time, only "red" will pop up because it prevents the event from bubbled.
2. Event Capture
Since there is a bubbling of events, there can be a capture of events, which is a reverse process. The difference is from the top element to the target element or from the target element to the top element.
Let's see 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)At this time, "yellow","green","red" pops up one by one, which is the capture of the event.
3. Block the default event
There are some default behaviors of html elements, such as the A tag, and there will be a jump action after clicking; the submit type input in the form form has a default submission jump event; the reset type input has a reset form behavior. If you want to block these browser default behavior, JavaScript provides you with a method.
var $a = document.getElementsByTagName("a")[0];$a.onclick = function(e){ alert("The jump action was blocked by me") e.preventDefault(); //return false;//It is also possible}<a href="http://keleyi.com">Ke Leyi</a>The default event is gone.Since return false and e.preventDefault() have the same effect, are there any differences? Of course there is.
The default behavior of event hosts can be organized only in HTML event attributes and DOM0-level event handling methods.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.