代码之家  ›  专栏  ›  技术社区  ›  John McCollum

如果没有传入回调,那么addEventListener中的事件对象来自哪里?

  •  1
  • John McCollum  · 技术社区  · 6 年前

    document.querySelector("input").addEventListener("input", function(event){
        document.querySelector("p").textContent = event.target.value;
    });
    

    event 参数,代码仍按预期工作:

    document.querySelector("input").addEventListener("input", function(){
        document.querySelector("p").textContent = event.target.value;
    });
    

    但是怎么做呢?我最好的猜测是,它在某种程度上可以通过 addEventListener

    JSFiddle

    1 回复  |  直到 6 年前
        1
  •  4
  •   Quentin    5 年前

    看到了吗 MDN :

    只读窗口属性事件返回当前由站点代码处理的事件。在事件处理程序的上下文之外,值总是未定义的。

    普遍支持,甚至在支持时,都会给代码带来潜在的脆弱性。


    addEventListener

    它是一个全球性的: window.event . 它只是碰巧只有在处理事件时才存在。

    兼容性 event 财产 window IE和Google Chrome支持,但Firefox不支持。