element.addEventListener DOM事件模型

https://developer.mozilla.org/zh-CN/docs/DOM/element.addEventListener

概述

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, thedocument itself, a window, or an XMLHttpRequest.

To register more than one event listener for the target, call addEventListener() for the same target but with different event types or capture parameters.

语法

target.addEventListener(typelistener[, useCapture]);
target.addEventListener(typelistener[, useCapture, aWantsUntrusted 非标准]); // Gecko/Mozilla only

type
A string representing the  event type to listen for.
listener
The object that receives a notification when an event of the specified type occurs. This must be an object implementing the EventListener interface, or simply a JavaScript  function.
useCapture   可选
If  trueuseCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered  listener before being dispatched to any  EventTarget beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See  DOM Level 3 Events for a detailed explanation. Note that this parameter is not optional in all browser versions. If not specified,  useCapture is  false.
aWantsUntrusted  非标准
If  true, the event can be triggered by untrusted content. See  Interaction between privileged and non-privileged pages.
Note:  useCapture became optional only in more recent versions of the major browsers; for example, it was not optional prior to Firefox 6. You should provide that parameter for broadest compatibility.

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
< html >
< head >
   < title >DOM Event Example</ title >
   < style type = "text/css" >
     #t { border: 1px solid red }
     #t1 { background-color: pink; }
   </ style >
   < script type = "application/javascript" >
 
   // Function to change the content of t2
   function modifyText() {
     var t2 = document.getElementById("t2");
     t2.firstChild.nodeValue = "three";   
   }
 
   // Function to add event listener to t
   function load() {
     var el = document.getElementById("t");
     el.addEventListener("click", modifyText, false);
   }
 
   document.addEventListener("DOMContentLoaded", load, false);
 
   </ script >
</ head >
< body >
< table id = "t" >
   < tr >< td id = "t1" >one</ td ></ tr >
   < tr >< td id = "t2" >two</ td ></ tr >
</ table >
</ body >
</ html >

在jsFiddle中查看

In the above example, modifyText() is a listener for click events registered using addEventListener(). A click anywhere on the table will bubble up to the handler and run modifyText().

If you want to pass parameters to the listener function, you have to use an anonymous function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
< html >
< head >
   < title >DOM Event Example</ title >
   < style type = "text/css" >
     #t { border: 1px solid red }
     #t1 { background-color: pink; }
   </ style >
   < script type = "text/javascript" >
 
   // Function to change the content of t2
   function modifyText(new_text) {
     var t2 = document.getElementById("t2");
     t2.firstChild.nodeValue = new_text;   
   }
 
   // Function to add event listener to t
   function load() {
     var el = document.getElementById("t");
     el.addEventListener("click", function(){modifyText("four")}, false);
   }
 
   </ script >
</ head >
< body onload = "load();" >
< table id = "t" >
   < tr >< td id = "t1" >one</ td ></ tr >
   < tr >< td id = "t2" >two</ td ></ tr >
</ table >
</ body >
</ html >

备注

为什么要使用addEventListener?

addEventListener is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that need to work well even if other libraries/extensions are used.
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements.

The alternative, older way to register event listeners is described below.

Adding a listener during event dispatch

If an EventListener is added to an EventTarget while it is processing an event, it will not be triggered by the current actions but may be triggered during a later stage of event flow, such as the bubbling phase.

Multiple identical event listeners

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause theEventListener to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the removeEventListener method.

The value of this within the handler

It is often desirable to reference the element from which the event handler was fired, such as when using a generic handler for a series of similar elements. When attaching a function using addEventListener() the value of this is changed—note that the value of this is passed to a function from the caller.

In the example above, the value of this within modifyText() when called from the click event is a reference to the table 't'. This is in contrast to the behavior that occurs if the handler is added in the HTML source:

1
2
< table id = "t" onclick = "modifyText();" >
. . .

The value of this within modifyText() when called from the onclick event will be a reference to the global (window) object.

Note: JavaScript 1.8.5 introduces the  Function.prototype.bind() method, which lets you specify the value that should be used as  this for all calls to a given function. This lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can later remove it.

旧版Internet Explorer 的 attachEvent方法

In Internet Explorer versions prior to IE 9, you have to use attachEvent rather than the standard addEventListener. To support IE, the example above can be modified to:

1
2
3
4
5
if (el.addEventListener) {
   el.addEventListener( 'click' , modifyText, false );
} else if (el.attachEvent)  {
   el.attachEvent( 'onclick' , modifyText);
}

There is a drawback to attachEvent, the value of this will be a reference to the window object instead of the element on which it was fired.

注册事件侦听器的传统方法

addEventListener() was introduced with the DOM 2 Events specification. Before then, event listeners were registered as follows:

1
2
3
4
5
6
7
// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;
 
// Using a function expression
element.onclick = function () {
     // ... function logic ...
};

This method replaces the existing click event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as blur (onblur),keypress (onkeypress), and so on.

Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

内存问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var i;
var els = document.getElementsByTagName( '*' );
 
// Case 1
for (i=0 ; i<els.length ; i++){
   els[i].addEventListener( "click" , function (e){ /*do something*/ }, false });
}
 
// Case 2
function processEvent(e){
   /*do something*/
}
 
for (i=0 ; i<els.length ; i++){
   els[i].addEventListener( "click" , processEvent, false });
}

In the first case, a new (anonymous) function is created at each loop turn. In the second case, the same previously declared function is used as an event handler. This results in smaller memory consumption. Moreover, in the first case, since no reference to the anonymous functions is kept, it is not possible to callelement.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to domyElement.removeEventListener("click", processEvent, false).

浏览器兼容性

  • Desktop 
  • Mobile
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 1.0 (1.7 or earlier) 9.0 7 1.0
useCapture made optional 1.0 6.0 9.0 11.60 (Yes)

Gecko 备注
  • Prior to Firefox 6, the browser would throw if the useCapture parameter was not explicitly <font face="'Courier New', 'Andale Mono', monospace">false</font>. Prior to Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6), addEventListener() would throw an exception if the listener parameter was null; now the method returns without error, but without doing anything.
WebKit 备注
  • Although WebKit has explicitly added [optional] to the useCapture parameter fairly recently, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值