簡體   English   中英

不使用jQuery觸發自定義事件

[英]trigger custom event without jQuery

我用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> 

如何在沒有jQuery的情況下觸發這個?

重要提示 :我需要知道事件類型和自定義數據

如果你想要精確復制jQuery的行為,你可能最好挖掘jQuery source code

如果您只想進行正常的事件調度和偵聽,請參閱CustomEvent以了解如何使用自定義數據調度事件,並參閱addEventListener以了解如何偵聽它。

你的例子可能看起來像

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

您可以使用自定義事件並在所需元素上調度它們。

快捷方式:

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

或者對於全球事件:

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

抓住它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM