在没有jQuery的情况下收听jQuery事件 [英] Listen to jQuery event without jQuery

查看:65
本文介绍了在没有jQuery的情况下收听jQuery事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法设置事件监听器,所以它捕获jQuery触发的事件?我想只使用普通(vanilla)JavaScript来收听事件。

Is there a way to set up an event listener, so it captures an event fired by jQuery? I want to use only plain (vanilla) JavaScript to listen to the event.

我设置了以下示例:

(function($) {

    $(document).on('sent_jquery_rec_jquery', function () {
        console.log('sent_jquery_rec_jquery');
    });

    $(document).on('sent_vanilla_rec_jquery', function () {
        console.log('sent_vanilla_rec_jquery');
    });

    document.addEventListener('sent_vanilla_rec_vanilla', function () {
        console.log('sent_vanilla_rec_vanilla');
    });

    document.addEventListener('sent_jquery_rec_vanilla', function () {
        console.log('sent_jquery_rec_vanilla');
    });

    document.dispatchEvent(new Event("sent_vanilla_rec_vanilla"));
    document.dispatchEvent(new Event("sent_vanilla_rec_jquery"));

    $(document).trigger('sent_jquery_rec_jquery');
    $(document).trigger('sent_jquery_rec_vanilla');

}(jQuery));

收到并记录的三件事是:

Three events which are received and logged are:


  • sent_vanilla_rec_vanilla

  • sent_vanilla_rec_jquery

  • sent_jquery_rec_jquery

当事件通过 $(document).trigger 发送时,事件监听器设置为 document.addEventListener 没有启动。这是什么原因,我怎么能让它工作?

When the event is sent via $(document).trigger, the event listener set up with document.addEventListener does not kick in. What's the reason for that, and how can I make it work?

推荐答案

JQuery 显然使用自定义事件系统,因此您无法通过常规事件监听jQuery事件监听器。上述票据提到IE< 9作为罪魁祸首,也许jQuery 3或4可以进行切换。

JQuery apparently uses a custom event system, so you can't listen to jQuery events with a regular event listener. The aforementioned ticket mentions IE <9 as the culprit here, maybe jQuery 3 or 4 could make the switch.

这篇关于在没有jQuery的情况下收听jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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