MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

翻譯不完整。請協助 翻譯此英文文件

EventTarget.addEventListener() 方法能將指定的事件監聽器註冊到 EventTarget 實作物件上。EventTarget 可能是 Document 中的 Element 物件、Document 物件本身、Window 物件,或是其它支援事件的物件(如:XMLHttpRequest)。

語法

target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only

參數

type
表示所監聽的 event type 名稱之字串。
listener
當監聽的事件發生時負責接收事件物件(Event 的實作物件)的物件。這個物件必須是事件監聽器(實作了 EventListener 介面),或是一個簡單的 JavaScript 函式
options 選擇性
An options object that specifies characteristics about the event listener. The available options are:
  • capture: A Boolean that indicates that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
  • once: A Boolean indicating that the listener should be invoked at most once after being added. If it is true, the listener would be removed automatically when it is invoked.
  • passive: A Boolean indicating that the listener will never call preventDefault(). If it does, the user agent should ignore it and generate a console warning.
  • mozSystemGroup: Available only in code running in XBL or in Firefox's chrome, it is a Boolean defining if the listener is added to the system group.
useCapture 選擇性
若為true, useCapture表示使用者想要初始接取機制。在初始接取機制後,所有指定型態的事件會在發送到任何上方DOM樹的EventTarget之前先發送到註冊的listener,從樹中冒泡而上的事件不會觸發用來接取機制的傾聽器,Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event .參考DOM Level 3 EventsJavaScript Event order關於更詳盡的解釋。useCapture的初始值為false.
註:For event listeners attached to the event target; the event is in the target phase, rather than capturing and bubbling phases. Events in the target phase will trigger all listeners on an element regardless of the useCapture parameter.
註: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 this parameter for broadest compatibility.
wantsUntrusted
If true, the listener will receive synthetic events dispatched by web content (the default is false for chrome and true for regular web pages). This parameter is only available in Gecko and is mainly useful for the code in add-ons and the browser itself. See Interaction between privileged and non-privileged pages for an example.

範例

一個簡易的事件監聽

HTML 內容

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

JavaScript 內容

// Function to change the content of t2
function modifyText() {
  var t2 = document.getElementById("t2");
  if (t2.firstChild.nodeValue == "three") {
    t2.firstChild.nodeValue = "two";
  } else {
    t2.firstChild.nodeValue = "three";
  }
}

// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);

在上述的範例中,modifyText() 是一個監聽器,監聽透過 addEventListener() 註冊的 click 事件。任何在這個表格內的點擊都會冒泡(bubble up)到這個事件處理器(handler)並執行 modifyText()

如果你要傳入任何參數到監聽器函式,你可以使用一個匿名函式。

匿名函數的事件監聽

HTML 內容

<table id="outside">
    <tr><td id="t1">one</td></tr>
    <tr><td id="t2">two</td></tr>
</table>

JavaScript 內容

// 改變 t2 內容的函數
function modifyText(new_text) {
  var t2 = document.getElementById("t2");
  t2.firstChild.nodeValue = new_text;    
}

// 為表格增加事件監聽的函數
var el = document.getElementById("outside");
el.addEventListener("click", function(){modifyText("four")}, false);

備註

為甚麼使用 addEventListener?

addEventListener 是註冊一個事件監聽器的方式,正如 W3C DOM 中所定義的。他的好處有這些:

  • 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 with other libraries/extensions.
  • 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, that event does not trigger the listener. However, that same listener 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 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 on which the event handler was fired, such as when using a generic handler for a set of similar elements.

When attaching a handler function to an element using addEventListener(), the value of this inside the handler is a reference to the element. It is the same as the value of the currentTarget property of the event argument that is passed to the handler.

If an event attribute (e.g., onclick) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value of this in a manner consistent with the use of addEventListener(); an occurrence of this within the code represents a reference to the element. Note that the value of this inside a function called by the code in the attribute value behaves as per standard rules. Therefore, given the following example:

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

The value of this within modifyText() when called via the onclick event is a reference to the global (window) object (or undefined in the case of strict mode).

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

This is an example with and without bind:

var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.onclick1 = function(event) {
    console.log(this.name); // undefined, as |this| is the element
  };
  this.onclick2 = function(event) {
    console.log(this.name); // 'Something Good', as |this| is bound to newly created object
  };
  element.addEventListener('click', this.onclick1, false);
  element.addEventListener('click', this.onclick2.bind(this), false); // Trick
}
var s = new Something(document.body);

A problem in the example above is that you cannot remove the listener with bind. Another solution is using a special function called handleEvent to catch any events:

var Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.handleEvent = function(event) {
    console.log(this.name); // 'Something Good', as this is bound to newly created object
    switch(event.type) {
      case 'click':
        // some code here...
        break;
      case 'dblclick':
        // some code here...
        break;
    }
  };

  // Note that the listeners in this case are |this|, not this.handleEvent
  element.addEventListener('click', this, false);
  element.addEventListener('dblclick', this, false);

  // You can properly remove the listeners
  element.removeEventListener('click', this, false);
  element.removeEventListener('dblclick', this, false);
}
var s = new Something(document.body);

Another way of handling the reference to this is to pass to the EventListener a function which calls the method of the object which fields want to be accessed:

class SomeClass {

  constructor() {
    this.name = 'Something Good';
  }

  register() {
    var that = this;
    window.addEventListener('keydown', function(e) {return that.someMethod(e);});
  }

  someMethod(e) {
    console.log(this.name);
    switch(e.keyCode) {
      case 5:
        // some code here...
        break;
      case 6:
        // some code here...
        break;
    }
  }

}

var myObject = new SomeClass();
myObject.register();

Internet Explorer 的 attachEvent 方法

在版本早於 IE 9 的 Internet Explorer, 必須使用 attachEvent 而非 addEventListener 監聽事件. 為了支援 IE, 可以參考下面的範例:

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.

瀏覽器相容性

You can work around addEventListener, removeEventListener, Event.preventDefault and Event.stopPropagation not being supported by IE 8 using the following code at the beginning of your script. The code supports the use of handleEvent and also the DOMContentLoaded event.

Note: useCapture is not supported, as IE 8 does not have any alternative method of it. Please also note that the following code only adds support to IE 8.

Also note that this IE 8 polyfill ONLY works in standards mode: a doctype declaration is required.

(function() {
  if (!Event.prototype.preventDefault) {
    Event.prototype.preventDefault=function() {
      this.returnValue=false;
    };
  }
  if (!Event.prototype.stopPropagation) {
    Event.prototype.stopPropagation=function() {
      this.cancelBubble=true;
    };
  }
  if (!Element.prototype.addEventListener) {
    var eventListeners=[];
    
    var addEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var self=this;
      var wrapper=function(e) {
        e.target=e.srcElement;
        e.currentTarget=self;
        if (typeof listener.handleEvent != 'undefined') {
          listener.handleEvent(e);
        } else {
          listener.call(self,e);
        }
      };
      if (type=="DOMContentLoaded") {
        var wrapper2=function(e) {
          if (document.readyState=="complete") {
            wrapper(e);
          }
        };
        document.attachEvent("onreadystatechange",wrapper2);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper2});
        
        if (document.readyState=="complete") {
          var e=new Event();
          e.srcElement=window;
          wrapper2(e);
        }
      } else {
        this.attachEvent("on"+type,wrapper);
        eventListeners.push({object:this,type:type,listener:listener,wrapper:wrapper});
      }
    };
    var removeEventListener=function(type,listener /*, useCapture (will be ignored) */) {
      var counter=0;
      while (counter<eventListeners.length) {
        var eventListener=eventListeners[counter];
        if (eventListener.object==this && eventListener.type==type && eventListener.listener==listener) {
          if (type=="DOMContentLoaded") {
            this.detachEvent("onreadystatechange",eventListener.wrapper);
          } else {
            this.detachEvent("on"+type,eventListener.wrapper);
          }
          eventListeners.splice(counter, 1);
          break;
        }
        ++counter;
      }
    };
    Element.prototype.addEventListener=addEventListener;
    Element.prototype.removeEventListener=removeEventListener;
    if (HTMLDocument) {
      HTMLDocument.prototype.addEventListener=addEventListener;
      HTMLDocument.prototype.removeEventListener=removeEventListener;
    }
    if (Window) {
      Window.prototype.addEventListener=addEventListener;
      Window.prototype.removeEventListener=removeEventListener;
    }
  }
})();

註冊 event listeners 的舊方法

addEventListener() was introduced with the DOM 2 Events 規範。在這之前,註冊 event listeners 的方法如下:

// Passing 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 ...
};

這個方法取代在元素上現有的 click event listener(s)。Similarly for other events and associated event handlers such as blur (onblur), keypress (onkeypress), and so on.

因為這是 DOM 0 的一部份, 這個方法被廣泛的支援且不需跨瀏覽器的程式碼; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

記憶體問題

var i;
var els = document.getElementsByTagName('*');

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

// 案例 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 iteration of the loop. 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, it is not possible to call element.removeEventListener because no reference to the anonymous function is kept. In the second case, it's possible to do myElement.removeEventListener("click", processEvent, false).

Improving scrolling performance with passive listeners

The default value for the passive option is false. Starting in Chrome 56 (desktop, Chrome for android, and android webview) the default value for touchstart and touchmove is true and calls to preventDefault() are not needed. To override this behavior, you simply set the passive option to false as shown in the example below. This change prevents the listener from blocking page rendering while a user is scrolling. A demo is available on the Google Developer site.

var elem = document.getElementById('elem');
elem.addEventListener('touchmove', function listener() {
  /* do something */
}, { passive: false });

規範

Specification Status Comment
DOM
The definition of 'EventTarget.addEventListener()' in that specification.
Living Standard  
DOM4
The definition of 'EventTarget.addEventListener()' in that specification.
Recommendation  
Document Object Model (DOM) Level 2 Events Specification
The definition of 'EventTarget.addEventListener()' in that specification.
Recommendation Initial definition

瀏覽器相容性

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 1.0[1][2] (Yes) 1.0 (1.7 or earlier)[3] 9.0[4] 7 1.0[1]
useCapture made optional 1.0 (Yes) 6 (6) 9.0 11.60 (Yes)
options parameter (with capture and passive values)[5]

49.0 (capture) 51.0 (passive)

No support 49 (49) No support (Yes) Landed in Nightly WebKit bug 158601
once value in the options parameter 55 No support 50 (50) No support 42 Landed in Nightly WebKit bug 149466
Passive defaults to true for touchstart and touchend 55 No support No support No support No support No support
Feature Android Webview Chrome for Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support

(Yes)[2]

(Yes)

(Yes) 1.0 (1.0)[3] 9.0 6.0 1.0[1]
useCapture made optional

(Yes)

(Yes)

(Yes) 6.0 (6) ? ? ?
options parameter (with capture and passive values)[5] 49.0 (capture) 51.0 (passive) 49.0 (capture) 51.0 (passive) No support 49.0 (49) ? (Yes) ?
once value in the options parameter 55 55 No support 50 (50) No support 42 ?
Passive defaults to true for touchstart and touchend 55 55 No support No support No support No support No support

[1] Although WebKit has explicitly added [optional] to the useCapture parameter as recently as June 2011, it had been working before the change. The new change landed in Safari 5.1 and Chrome 13.

[2] Before Chrome 49, the type and listener parameters were optional.

[3] Prior to Firefox 6, the browser would throw an error if the useCapture parameter was not explicitly false. 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.

[4] Older versions of Internet Explorer support the proprietary EventTarget.attachEvent method instead.

[5] For backwards compatibility, browsers that support options allow the third parameter to be either options or Boolean.

參見

文件標籤與貢獻者

標籤: 
 此頁面的貢獻者: jackblackevo, Shiyou, alk03073135, polyamide, changbenny
 最近更新: jackblackevo,