mozilla
您的搜索结果

    EventTarget.addEventListener()

    翻译正在进行中。

    概述

    addEventListener() 方法将指定的事件监听器注册到目标对象上,当该对象触发指定的事件时,指定的回调函数就会被执行。 监听事件 可以是一个文档上的元素,  document 本身, window, 或者 XMLHttpRequest.

    语法

    target.addEventListener(type, listener[, useCapture]);
    target.addEventListener(type, listener[, useCapture, wantsUntrusted  ]); // Gecko/Mozilla only
    
    type
    表示所监听事件的类型[zh-CN]的一个字符串。
    listener
    当指定的事件类型发生时被通知到的一个对象。该参数必是实现EventListener接口的一个对象或函数。
    useCapture  可选
    如果值为true, useCapture 表示用户希望发起捕获。 在发起捕获之后, 只要Dom子树下发生了该事件类型,都会先被派发到该注册监听器,然后再被派发到Dom子树中的注册监听器中。并且向上冒泡的事件不会触发那些发起捕获的事件监听器。进一步的解释可以查看 DOM Level 3 Events 文档。 请注意该参数并不是在所有的浏览器版本中都是可选的。如果没有指定, useCapture 默认为false 。
    Note: 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 仅仅在现代浏览器比较靠前的几个版本中是可选的。 例如 Firefox 6以前的版本都不是可选的。
    wantsUntrusted 
    如果该值为true, 则事件能够被不可信的内容所触发。请见 Interaction between privileged and non-privileged pages.

    例子

    添加一个简单的事件监听器

    HTML Content

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

    JavaScript Content

    // 改变t2的函数
    function modifyText() {
      var t2 = document.getElementById("t2");
      if (t2.firstChild.nodeValue == "three") {
        t2.firstChild.nodeValue = "two";
      } else {
        t2.firstChild.nodeValue = "three";
      }
    }
    
    // 为table添加事件监听器
    var el = document.getElementById("outside");
    el.addEventListener("click", modifyText, false);
     
     
     
     
     
     
     
     
     
     
     
     
     

    在上个例子中,modifyText() 是一个click事件监听器,通过使用addEventListenter注册到table对象上。在表格中任何位置单击都会触动事件并执行modifyText()。

    如果你想传参到事件监听函数中,你可以使用匿名函数。

    带有匿名函数的事件监听器

    HTML Content

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

    JavaScript Content

    // 改变t2值的函数
    function modifyText(new_text) {
      var t2 = document.getElementById("t2");
      t2.firstChild.nodeValue = new_text;    
    }
     
    // 为table对象添加事件监听器
    var el = document.getElementById("outside");
    el.addEventListener("click", function(){modifyText("four")}, false);
     
     
     
     
     
     
     
     
     

    备注

    为什么要使用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});
    }
    
    

    在第一种情况下,每个循环中都会创建一个新的(匿名)函数。在第二种情况下,会使用先前声明的相同的函数作为事件处理器。这样的结果是占用的存储空间更小。而且,在第一种情况中,由于没有保持到匿名函数的引用,它不可能被调用 element.removeEventListener,这是因为我们没有一个可参考的处理器,而在第二种情况,它可以被 myElement.removeEventListener("click", processEvent, false)

    浏览器兼容性

    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)
    Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support 1.0 1.0 (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 (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.

    相关链接

    规范

    DOM Level 2 Events: EventTarget.addEventListener

    DOM Level 3 Events: EventTarget.addEventListener

    文档标签和贡献者

    此页面的贡献者有: Ninneo, focus, ziyunfei, Josephok, teoli, yfdyh000, sunorry, baiya, Guangxue.Zhang
    最后编辑者: Ninneo,