trigger custom event without jQuery

前端 未结 2 1287
难免孤独
难免孤独 2020-12-16 13:10

I\'m triggering some DOM Events with jQuery triggerHandler()

相关标签:
2条回答
  • 2020-12-16 13:56

    You can use Custom Events and dispatch them on element you want.

    0 讨论(0)
  • 2020-12-16 14:05

    If you want an exact replication of jQuery's behaviour, you're probably best off digging through the 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.

    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'}}));
    
    0 讨论(0)
提交回复
热议问题