简体   繁体   English

不使用jQuery触发自定义事件

[英]trigger custom event without jQuery

I'm triggering some DOM Events with jQuery triggerHandler() 我用jQuery triggerHandler()触发了一些DOM事件

 <!DOCTYPE html> <html> <head> <title>stackoverflow</title> <script src="http://ajax.googleapis.com:80/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <script> $(document).ready(function() { $(document).on('hey', function(customEvent, originalEvent, data) { console.log(customEvent.type + ' ' + data.user); // hey stackoverflow }); // how to this in vanilla js $(document).triggerHandler('hey', [{}, { 'user': 'stackoverflow' }]) }); </script> </body> </html> 

How can I trigger this without jQuery? 如何在没有jQuery的情况下触发这个?

Important : I need to know the event type and the custom data 重要提示 :我需要知道事件类型和自定义数据

If you want an exact replication of jQuery's behaviour, you're probably best off digging through the jQuery source code . 如果你想要精确复制jQuery的行为,你可能最好挖掘jQuery source code

If you just want to do normal event dispatching and listening, see CustomEvent for how to dispatch an event with custom data and addEventListener for how to listen to it. 如果您只想进行正常的事件调度和侦听,请参阅CustomEvent以了解如何使用自定义数据调度事件,并参阅addEventListener以了解如何侦听它。

Your example would probably look something like 你的例子可能看起来像

document.addEventListener('hey', function(customEvent)
{
    console.log(customEvent.type + ' ' + customEvent.detail.user); // hey stackoverflow
});
document.dispatchEvent(new CustomEvent('hey', {'detail': {'user': 'stackoverflow'}}));

您可以使用自定义事件并在所需元素上调度它们。

The quick & easy way: 快捷方式:

$('#element').trigger("mycustomevent");

or for global event: 或者对于全球事件:

$(document).trigger("mycustomevent");

catching it: 抓住它:

$('#element').on("mycustomevent", function(e){
    // do something
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM