How to trigger event in JavaScript?

前端 未结 18 1865
情深已故
情深已故 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:04

    If you don't want to use jQuery and aren't especially concerned about backwards compatibility, just use:

    let element = document.getElementById(id);
    element.dispatchEvent(new Event("change")); // or whatever the event type might be
    

    See the documentation here and here.

    EDIT: Depending on your setup you might want to add bubbles: true:

    let element = document.getElementById(id);
    element.dispatchEvent(new Event('change', { 'bubbles': true }));
    

提交回复
热议问题