document.addEventListener与$(document).on [英] document.addEventListener vs. $(document).on

查看:131
本文介绍了document.addEventListener与$(document).on的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以某种方式发现了将eventlisteners添加到文档中的一些奇怪行为。在向HTMLElements添加侦听器时,可以正常地向文档添加侦听器不起作用。但奇怪的是,使用jQuery使它工作。

I somehow found a bit strange behavior of adding eventlisteners to document. While adding listeners to HTMLElements works fine adding a listener to document doesn't work. But the strange thing is, that using jQuery makes it work.

所以有人可以解释一下,为什么这两个函数没有做同样的事情?

So can someone explain, why this two functions are not doing the exact same thing?

["customEvent1", "customEvent2"].forEach(
    (event: string) => {
        document.addEventListener(event, () => this.eventHandler());
    });

$(document).on("customEvent1 customEvent2", () => this.eventHandler());

编辑:
嗯,它确实存在对环境的一些误解。

Well it seams that there is some misunderstanding about the environment.


  1. 该函数被类包围

  2. 我正在使用TypeScript / ES6

  3. EventHandler是一个类方法

  4. 使用 $(document).trigger(customEvent1);

  1. The function is surrounded by a class
  2. I'm using TypeScript/ES6
  3. the EventHandler is a class method
  4. the custom event is triggered with $(document).trigger("customEvent1");


推荐答案

如果使用<$ c $,jQuery不会创建本机事件c> $(document).trigger(customEvent2); jquery src / event / trigger.js ),它只模拟原生事件处理。

jQuery does not create a native event if you use $(document).trigger("customEvent2"); (jquery src/event/trigger.js), it only emulates the native event handling.

所以如果你注册一个事件处理程序使用 document.addEventListener 然后你不能使用 $(document).trigger(来处理这些事件。

So if you register an event handler using document.addEventListener then your cannot use $(document).trigger( for those events.

但是如果你使用本机代码创建和发送一个事件:

But if you create and dispatch an event using native code:

var event = new Event('customEvent1');
document.dispatchEvent(event);

然后你可以用 document.addEventListener 和jQuery的 .on

Then you can catch it with both document.addEventListener and jQuery's .on

这篇关于document.addEventListener与$(document).on的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆