How to trigger event in JavaScript?

前端 未结 18 1910
情深已故
情深已故 2020-11-21 04:48

I have attached an event to a text box using addEventListener. It works fine. My problem arose when I wanted to trigger the event programmatically from another

18条回答
  •  梦如初夏
    2020-11-21 05:11

    You can use fireEvent on IE 8 or lower, and W3C's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.

    Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:

    var event; // The custom event that will be created
    if(document.createEvent){
        event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
        event.eventName = "dataavailable";
        element.dispatchEvent(event);
    } else {
        event = document.createEventObject();
        event.eventName = "dataavailable";
        event.eventType = "dataavailable";
        element.fireEvent("on" + event.eventType, event);
    }
    

提交回复
热议问题