Home  >  Article  >  JavaScript DOM object learning event stream addEventListener() usage tutorial

JavaScript DOM object learning event stream addEventListener() usage tutorial

伊谢尔伦
伊谢尔伦Original
2017-07-12 11:08:351933browse

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 31cc4cc06567af2f956c109cd4342ed2 元素插入到 dc6dce4a544fdca2df29d5ac0ea9906b 元素中,用户点击 e388a4556c0f65e1904146cc1a846bee 元素, 哪个元素的 "click" 事件先被触发呢?

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

在 捕获 中,外部元素的事件会先被触发,然后才会触发内部元素的事件,即: dc6dce4a544fdca2df29d5ac0ea9906b 元素的点击事件先触发 ,然后再触发 e388a4556c0f65e1904146cc1a846bee 元素的点击事件。

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