element.addEventListener

  • 版本网址缩略名: DOM/element.addEventListener
  • 版本标题: element.addEventListener
  • 版本 id: 33626
  • 创建于:
  • 创建者: ziyunfei
  • 是否是当前版本?
  • 评论 page created, 1361 words added

修订内容

概述

addEventListener() registers a single event listener on a single target. The event target may be a single element in a document, the document 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(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, aWantsUntrusted {{ Non-standard_inline() }}]); // 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  {{ optional_inline() }}
If true, useCapture 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 {{ Non-standard_inline() }}
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.

例子

 <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> 

{{ JSFiddleLink("madBYK/UumUP") }}

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.

 <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 the EventListener 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:

<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:

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:

// 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.

内存问题

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 call element.removeEventListener because we do not have a reference to the handler, while in the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

浏览器兼容性

{{ CompatibilityTable() }}

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0 {{ CompatGeckoDesktop("1") }} 9.0 7 1.0
useCapture made optional 1.0 6.0 9.0 11.60 {{ CompatVersionUnknown() }}
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 1.0 {{ CompatGeckoMobile("1") }} 9.0 6.0 1.0

Gecko 备注

  • Prior to Firefox 6, the browser would throw if the useCapture parameter was not explicitly false. Prior to Gecko 9.0 {{ geckoRelease("9.0") }}, 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.

相关链接

规范

DOM Level 2 Events: EventTarget.addEventListener

DOM Level 3 Events: EventTarget.addEventListener

{{ languages( { "fr": "fr/DOM/element.addEventListener", "ja": "ja/DOM/element.addEventListener", "en": "en/DOM/element.addEventListener", "pl": "pl/DOM/element.addEventListener" } ) }}

修订版来源

<h2 id="Summary" name="Summary">概述</h2>
<p><code>addEventListener()</code> registers a single event listener on a single target. The <a href="/zh-cn/DOM/EventTarget" title="zh-cn/DOM/EventTarget">event target</a> may be a single <a href="/zh-cn/DOM/element" title="zh-cn/DOM/element">element</a> in a document, the <code><a href="/zh-cn/DOM/document" title="zh-cn/DOM/document">document</a></code> itself, a <code><a href="/zh-cn/DOM/window" title="zh-cn/DOM/window">window</a></code>, or an <code><a href="/zh-cn/DOM/XMLHttpRequest" title="zh-cn/XMLHttpRequest">XMLHttpRequest</a></code>.</p>
<p>To register more than one event listener for the target, call <code>addEventListener()</code> for the same target but with different event types or capture parameters.</p>
<h2 id="Syntax" name="Syntax">语法</h2>
<p><code><em>target</em>.addEventListener(<em>type</em>, <em>listener</em>[, <em>useCapture</em></code>]<code>);</code><br> <code><em>target</em>.addEventListener(<em>type</em>, <em>listener</em>[, <em>useCapture</em></code><code>,</code> <code><em>aWantsUntrusted </em></code>{{ Non-standard_inline() }}<code>]);</code> // Gecko/Mozilla only</p>
<dl> <dt><code>type</code></dt> <dd>A string representing the <a class="internal" href="/zh-cn/DOM/event.type" title="zh-cn/DOM/Event.type">event type</a> to listen for.</dd> <dt><code>listener</code></dt> <dd>The object that receives a notification when an event of the specified type occurs. This must be an object implementing the <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener"><code>EventListener</code></a> interface, or simply a JavaScript <a href="/zh-cn/JavaScript/Guide/Functions" title="zh-cn/Core_JavaScript_1.5_Guide/Functions">function</a>.</dd> <dt><code>useCapture</code>  {{ optional_inline() }}</dt> <dd>If <code>true</code>, <code>useCapture</code> indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered <code>listener</code> before being dispatched to any <code>EventTarget</code> beneath it in the DOM tree. Events which are bubbling upward through the tree will not trigger a listener designated to use capture. See <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#event-flow" title="http://www.w3.org/TR/DOM-Level-3-Events/#event-flow">DOM Level 3 Events</a> for a detailed explanation. Note that this parameter is not optional in all browser versions. If not specified, <code>useCapture</code> is <code>false</code>.</dd> <dt><code>aWantsUntrusted</code> {{ Non-standard_inline() }}</dt> <dd>If <code>true</code>, the event can be triggered by untrusted content. See <a href="/zh-cn/Code_snippets/Interaction_between_privileged_and_non-privileged_pages" title="zh-cn/Code snippets/Interaction between privileged and non-privileged pages">Interaction between privileged and non-privileged pages</a>.</dd>
</dl>
<div class="note"><strong>Note:</strong> <code>useCapture</code> 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.</div>
<dl><br>
</dl>
<h2 id="Example" name="Example">例子</h2>
<pre class="brush: html"> &lt;html&gt;
 &lt;head&gt;
   &lt;title&gt;DOM Event Example&lt;/title&gt;
   &lt;style type="text/css"&gt;
     #t { border: 1px solid red }
     #t1 { background-color: pink; }
   &lt;/style&gt;
   &lt;script type="application/javascript"&gt;

   // 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);

   &lt;/script&gt; 
 &lt;/head&gt; 
 &lt;body&gt; 
 &lt;table id="t"&gt; 
   &lt;tr&gt;&lt;td id="t1"&gt;one&lt;/td&gt;&lt;/tr&gt; 
   &lt;tr&gt;&lt;td id="t2"&gt;two&lt;/td&gt;&lt;/tr&gt; 
 &lt;/table&gt; 
 &lt;/body&gt; 
 &lt;/html&gt; 
</pre>
<p>{{ JSFiddleLink("madBYK/UumUP") }}</p>
<p>In the above example, <code>modifyText()</code> is a listener for <code>click</code> events registered using <code>addEventListener()</code>. A click anywhere on the table will bubble up to the handler and run <code>modifyText()</code>.</p>
<p>If you want to pass parameters to the listener function, you have to use an anonymous function.</p>
<pre class="brush: html"> &lt;html&gt;
 &lt;head&gt;
   &lt;title&gt;DOM Event Example&lt;/title&gt;
   &lt;style type="text/css"&gt;
     #t { border: 1px solid red }
     #t1 { background-color: pink; }
   &lt;/style&gt;
   &lt;script type="text/javascript"&gt;

   // 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", <strong><strong>function(){modifyText("four")}</strong></strong>, false); 
   } 

   &lt;/script&gt; 
 &lt;/head&gt; 
 &lt;body onload="load();"&gt; 
 &lt;table id="t"&gt; 
   &lt;tr&gt;&lt;td id="t1"&gt;one&lt;/td&gt;&lt;/tr&gt; 
   &lt;tr&gt;&lt;td id="t2"&gt;two&lt;/td&gt;&lt;/tr&gt; 
 &lt;/table&gt; 
 &lt;/body&gt; 
 &lt;/html&gt; 
</pre>
<h2 id="备注">备注</h2>
<h3 id="Why_use_addEventListener.3F" name="Why_use_addEventListener.3F">为什么要使用<code>addEventListener</code>?</h3>
<p><code>addEventListener</code> is the way to register an event listener as specified in W3C DOM. Its benefits are as follows:</p>
<ul> <li>It allows adding more than a single handler for an event. This is particularly useful for <a href="/zh-cn/DHTML" title="zh-cn/DHTML">DHTML</a> libraries or <a href="/zh-cn/Extensions" title="zh-cn/Extensions">Mozilla extensions</a> that need to work well even if other libraries/extensions are used.</li> <li>It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)</li> <li>It works on any DOM element, not just HTML elements.</li>
</ul>
<p>The alternative, <a href="#Older_way_to_register_event_listeners">older way to register event listeners</a> is described below.</p>
<h3 id="Adding_a_listener_during_event_dispatch" name="Adding_a_listener_during_event_dispatch">Adding a listener during event dispatch</h3>
<p>If an <code>EventListener</code> is added to an <code>EventTarget</code> 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.</p>
<h3 id="Multiple_identical_event_listeners" name="Multiple_identical_event_listeners">Multiple identical event listeners</h3>
<p>If multiple identical <code>EventListener</code>s are registered on the same <code>EventTarget</code> with the same parameters, the duplicate instances are discarded. They do not cause the <code>EventListener</code> to be called twice, and since the duplicates are discarded, they do not need to be removed manually with the <a href="/zh-cn/DOM/element.removeEventListener" title="zh-cn/DOM/element.removeEventListener">removeEventListener</a> method.</p>
<h3 id="The_value_of_this_within_the_handler" name="The_value_of_this_within_the_handler">The value of <code>this</code> within the handler</h3>
<p>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 <code>addEventListener()</code> the value of <code>this</code> is changed—note that the value of <code>this</code> is passed to a function from the caller.</p>
<p>In the example above, the value of <code>this</code> within <code>modifyText()</code> 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:</p>
<pre class="brush: html">&lt;table id="t" onclick="modifyText();"&gt;
. . .
</pre>
<p>The value of <code>this</code> within <code>modifyText()</code> when called from the onclick event will be a reference to the global (window) object.</p>
<div class="note"><strong>Note:</strong> JavaScript 1.8.5 introduces the <code><a href="/zh-cn/JavaScript/Reference/Global_Objects/Function/bind" title="zh-cn/JavaScript/Reference/Global Objects/Function/bind">Function.prototype.bind()</a></code> method, which lets you specify the value that should be used as <code>this</code> 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.</div>
<h3 id="Compatibility" name="Compatibility">旧版Internet Explorer 的 attachEvent方法</h3>
<p>In Internet Explorer versions prior to IE 9, you have to use <code><a class="external" href="http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx">attachEvent</a></code> rather than the standard <code>addEventListener</code>. To support IE, the example above can be modified to:</p>
<pre class="brush: js">if (el.addEventListener) {
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent)  {
  el.attachEvent('onclick', modifyText);
}
</pre>
<p>There is a drawback to <code>attachEvent</code>, the value of <code>this</code> will be a reference to the <code>window</code> object instead of the element on which it was fired.</p>
<h3 id="Older_way_to_register_event_listeners" name="Older_way_to_register_event_listeners">注册事件侦听器的传统方法</h3>
<p><code>addEventListener()</code> was introduced with the DOM 2 <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events">Events</a> specification. Before then, event listeners were registered as follows:</p>
<pre class="brush: js">// 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 ...
};
</pre>
<p>This method replaces the existing <code>click</code> event listener(s) on the element if there are any. Similarly for other events and associated event handlers such as <code>blur</code> (<code>onblur</code>), <code>keypress</code> (<code>onkeypress</code>), and so on.</p>
<p>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 <code>addEventListener()</code> are needed.</p>
<h3 id="Memory_issues" name="Memory_issues">内存问题</h3>
<pre class="brush: js">var i;
var els = document.getElementsByTagName('*');

// Case 1
for(i=0 ; i&lt;els.length ; i++){
  els[i].addEventListener("click", function(e){/*do something*/}, false});
}

// Case 2
function processEvent(e){
  /*do something*/
}

for(i=0 ; i&lt;els.length ; i++){
  els[i].addEventListener("click", processEvent, false});
}

</pre>
<p>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 call <code><a href="/zh-cn/DOM/element.removeEventListener" title="zh-cn/DOM/element.removeEventListener">element.removeEventListener</a></code> because we do not have a reference to the handler, while in the second case, it's possible to do <code>myElement.removeEventListener("click", processEvent, false)</code>.</p>
<h2 id="Browser_Compatibility" name="Browser_Compatibility">浏览器兼容性</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Chrome</th> <th>Firefox (Gecko)</th> <th>Internet Explorer</th> <th>Opera</th> <th>Safari (WebKit)</th> </tr> <tr> <td>Basic support</td> <td>1.0</td> <td>{{ CompatGeckoDesktop("1") }}</td> <td>9.0</td> <td>7</td> <td>1.0</td> </tr> <tr> <td><code>useCapture</code> made optional</td> <td>1.0</td> <td>6.0</td> <td>9.0</td> <td>11.60</td> <td>{{ CompatVersionUnknown() }}</td> </tr> </tbody> </table>
</div>
<div id="compat-mobile"> <table class="compat-table"> <tbody> <tr> <th>Feature</th> <th>Android</th> <th>Firefox Mobile (Gecko)</th> <th>IE Mobile</th> <th>Opera Mobile</th> <th>Safari Mobile</th> </tr> <tr> <td>Basic support</td> <td>1.0</td> <td>{{ CompatGeckoMobile("1") }}</td> <td>9.0</td> <td>6.0</td> <td>1.0</td> </tr> </tbody> </table>
</div>
<h4 id="Gecko_备注">Gecko 备注</h4>
<ul> <li>Prior to Firefox 6, the browser would throw if the <code>useCapture</code> parameter was not explicitly <font face="'Courier New', 'Andale Mono', monospace"><span style="line-height: normal;">false</span></font>. Prior to Gecko 9.0 {{ geckoRelease("9.0") }}, <code>addEventListener()</code> would throw an exception if the <code>listener</code> parameter was <code>null</code>; now the method returns without error, but without doing anything.</li>
</ul>
<h4 id="WebKit_备注">WebKit 备注</h4>
<ul> <li>Although WebKit has explicitly added <code>[optional]</code> to the <code>useCapture</code> parameter <a class="external" href="http://trac.webkit.org/changeset/89781">fairly recently</a>, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.</li>
</ul>
<h2 id="Specification" name="Specification">相关链接</h2>
<ul> <li><a href="/zh-cn/DOM/element.removeEventListener" title="zh-cn/DOM/element.removeEventListener">element.removeEventListener()</a></li> <li><a href="/zh-cn/DOM/Creating_and_triggering_events" title="https://developer.mozilla.org/zh-cn/DOM/Creating_and_triggering_custom_events">Creating and triggering custom events</a></li> <li><a class="external" href="http://www.quirksmode.org/js/this.html" title="http://www.quirksmode.org/js/this.html">More details on the use of <code>this</code> in event handlers</a></li>
</ul>
<h2 id="Specification" name="Specification">规范</h2>
<p><a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener" title="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget-addEventListener">DOM Level 2 Events: EventTarget.addEventListener</a></p>
<p><a class="external" href="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener" style="text-decoration: none; color: rgb(51, 102, 153) !important; cursor: default; " title="http://dev.w3.org/2006/webapi/DOM-Level-3-Events/html/DOM3-Events.html#events-EventTarget-addEventListener">DOM Level 3 Events: EventTarget.addEventListener</a></p>
<p>{{ languages( { "fr": "fr/DOM/element.addEventListener", "ja": "ja/DOM/element.addEventListener", "en": "en/DOM/element.addEventListener", "pl": "pl/DOM/element.addEventListener" } ) }}</p>
恢复到这个版本