search
HomeheadlinesJavaScript DOM object learning event stream addEventListener() usage tutorial

addEventListener is used to register event processing program, which is attachEvent in IE. Why do we talk about addEventListener instead of attachEvent? Firstly, attachEvent is relatively simple, and secondly, addEventListener is the standard content in DOM.

Learn the video course of our php Chinese website: Dugu Jiujian (3)_JavaScript video tutorial

##Introduction

addEventListener registers an event handler for the document node, document, window or XMLHttpRequest. In the past, we usually used Syntax

element.addEventListener(event, function, useCapture);

The first parameter is the type of event (such as "click" or "mousedown").

The second parameter is the function called after the event is triggered .

The third parameter is a Boolean value used to describe whether the event is bubbling or capturing. This parameter is optional.

Note: Do not use the "on" prefix. For example, use "click" instead of "onclick".

You can

use the function name to reference the external function:

element.addEventListener("click", function(){ alert("Hello World!"); });
element.addEventListener("click", myFunction);function myFunction() {
    alert ("Hello World!");
}

addEventListener - event stream

Speaking of addEventListener, we have to talk about the event stream. It is easier to explain later by talking about event flow first.

When an event occurs, it is divided into three stages:

Capture stage Starting from the root node and going down, it is detected whether each node has registered an event handler. If an event handler is registered and useCapture is true, the event handler is called. (There is no such phase in IE.)

Target phase Triggers the event handler registered in the target object itself, also called the normal event dispatch phase.

Bubble stage From the target node to the root node, detect whether each node has an event handler registered. If an event handler is registered and useCapture is false, the event handler is called.

Example

<div id="div1">   <div id="div2">     <div id="div3">       <div id="div4">       </div>     </div>   </div> </div>

If you click the mouse on d3, the event flow is as follows:

Capture phase Check whether there is an event handler with useCapture as true at div1. If If so, execute the program, and then process div2 similarly.

Target stage At div3, it is found that div3 is the node clicked by the mouse, so this is the target stage. If there is an event handler, the program will be executed, regardless of whether useCapture is true or false.

The bubbling phase detects whether there is an event handler with useCapture set to false at div2. If there is, execute the program, and then process div1 similarly.

Note that in the above capture phase and bubbling phase, there should actually be nodes above div1, such as body, but this will not be discussed here.

addEventListener - The third parameter useCapture

addEventListener has three parameters: the first parameter indicates the event name (excluding on, such as "click"); the second parameter indicates the event to be received The processing function; the third parameter is useCapture, which will be explained in this article.

<div id="outDiv">   <div id="middleDiv">     <div id="inDiv">请在此点击鼠标。</div>   </div> </div>
<div id="info"></div>
var outDiv = document.getElementById("outDiv"); 
var middleDiv = document.getElementById("middleDiv"); 
var inDiv = document.getElementById("inDiv"); 
var info = document.getElementById("info");   
outDiv.addEventListener("click", function () { info.innerHTML += "outDiv" + "<br>"; }, false); 
middleDiv.addEventListener("click", function () { info.innerHTML += "middleDiv" + "<br>"; }, false); 
inDiv.addEventListener("click", function () { info.innerHTML += "inDiv" + "<br>"; }, false);

The above is the code we tested. The order of triggering is determined based on the display of info. There are three addEventListeners, and the optional values ​​​​of useCapture are true and false, so 2*2*2, you can get 8 segments. different procedures.

When all are false, the triggering order is: inDiv, middleDiv, outDiv;

When all are true, the triggering order is: outDiv, middleDiv, inDiv;

outDiv is true, and when the others are false, the triggering order is: outDiv, inDiv, middleDiv;

When middleDiv is true, and the others are false, the triggering order is: middleDiv, inDiv, outDiv;

……

Finally come to the following conclusion:

The triggering order of true is always before false;

If multiple ones are true, the outer layer is triggered before the inner layer ;

If multiple ones are false, the inner layer is triggered before the outer layer.

Add event handle to Window object

window.addEventListener("resize", function(){
    document.getElementById("demo").innerHTML = sometext;
});

Pass parameters

When passing parameter values, use "

Anonymous function" to call the function with parameters:

var p1 = 5;
var p2 = 7;
document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1, p2);
});
function myFunction(a, b) {
    var result = a * b;
    document.getElementById("demo").innerHTML = result;
}

事件冒泡或事件捕获?

事件传递有两种方式:冒泡与捕获。

事件传递定义了元素事件触发的顺序。 如果你将

元素插入到

元素中,用户点击

元素, 哪个元素的 "click" 事件先被触发呢?

在 冒泡 中,内部元素的事件会先被触发,然后再触发外部元素,即:

元素的点击事件先触发,然后会触发

元素的点击事件。

在 捕获 中,外部元素的事件会先被触发,然后才会触发内部元素的事件,即:

元素的点击事件先触发 ,然后再触发

元素的点击事件。

addEventListener() 方法可以指定 "useCapture" 参数来设置传递类型:

addEventListener(event, function, useCapture);

默认值为 false, 即冒泡传递,当值为 true 时, 事件使用捕获传递。

document.getElementById("myDiv").addEventListener("click", myFunction, true);

一般情况下,如果给一个dom对象绑定同一个事件,只有最后一个会生效,比如: 

document.getElementById("btn").onclick = method1; 
document.getElementById("btn").onclick = method2; 
document.getElementById("btn").onclick = method3;

那么将只有method3生效。 
如果是Mozilla系列,用addEventListener可以让多个事件按顺序都实现,比如: 

var btn1Obj = document.getElementById("btn1"); 
//element.addEventListener(type,listener,useCapture); 
btn1Obj.addEventListener("click",method1,false); 
btn1Obj.addEventListener("click",method2,false); 
btn1Obj.addEventListener("click",method3,false);

执行顺序为method1->method2->method3 
如果是ie系列,用attachEvent可以让多个事件按顺序都实现,比如: 

var btn1Obj = document.getElementById("btn1"); 
//object.attachEvent(event,function); 
btn1Obj.attachEvent("onclick",method1); 
btn1Obj.attachEvent("onclick",method2); 
btn1Obj.attachEvent("onclick",method3);

执行顺序为method3->method2->method1 

相关内容推荐:

1. Javascript 的addEventListener()及attachEvent()区别分析

2. 解析js中addEventListener()与removeEventListener()

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.