How to trigger event in JavaScript?

前端 未结 18 1938
情深已故
情深已故 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条回答
  •  Happy的楠姐
    2020-11-21 05:01

    function fireMouseEvent(obj, evtName) {
        if (obj.dispatchEvent) {
            //var event = new Event(evtName);
            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(evtName, true, true, window,
                    0, 0, 0, 0, 0, false, false, false, false, 0, null);
            obj.dispatchEvent(event);
        } else if (obj.fireEvent) {
            event = document.createEventObject();
            event.button = 1;
            obj.fireEvent("on" + evtName, event);
            obj.fireEvent(evtName);
        } else {
            obj[evtName]();
        }
    }
    
    var obj = document.getElementById("......");
    fireMouseEvent(obj, "click");
    

提交回复
热议问题