Trigger event with parameters

前端 未结 3 1166
鱼传尺愫
鱼传尺愫 2021-02-04 03:09

This is pretty annoying. I want to just trigger an event in javascript. I need to pass the event object into the parameters as usual and an additional custom parameter.

3条回答
  •  -上瘾入骨i
    2021-02-04 03:15

    Creating an event

    To create a simple event, use the Event constructor.

    var event = document.createEvent('MyEvent');
    

    However, if you want to pass data along with the event use the CustomEvent constructor instead.

    var event = CustomEvent('MyEvent', { 'detail': 'Wow, my very own Event!' });
    

    Dispatching the event

    You can then raise the event with targetElement.dispatchEvent.

    var elem =document.getElementById('myElement');
    elem.dispatchEvent(event);
    

    Catching the event

    elem.addEventListener('MyEvent', function (e) { console.log(e.detail); }, false);
    

    For older browsers( Pre-IE9)

    You have to use the document.createEvent function.

    // Create the event.
    var event = document.createEvent('Event');
    
    // Define that the event name is 'build'.
    event.initEvent('MyEvent', true, true);
    
    //Any Element can dispatch the event
    elem.dispatchEvent(event);
    

    Note that this method is deprecated and should only be used for compatibility purposes.

    More help : https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events: MDN: Creating_and_triggering_events

提交回复
热议问题