Javascript dispatchEvent click is not working in IE9 and IE10

岁酱吖の 提交于 2019-12-03 08:44:32
Marco Pappalardo

I have had the same issue with custom events some time ago and solved by using the code found in this other question: Custom events in IE without using libraries

Actually you don't need to use all the code, they are 3 function to use as wrapper for browser compatibility.

But I also suggest you to use the .click method which would solve your problem more easily (at least for normal click) http://www.w3schools.com/jsref/met_html_click.asp

so just do

document.getElementById("loginButton").click();

I am pasting here the code by sergey gospodarets from the other question, which could be useful.

    function triggerEvent(el,eventName){
        var event;
        if(document.createEvent){
            event = document.createEvent('HTMLEvents');
            event.initEvent(eventName,true,true);
        }else if(document.createEventObject){// IE < 9
            event = document.createEventObject();
            event.eventType = eventName;
        }
        event.eventName = eventName;
        if(el.dispatchEvent){
            el.dispatchEvent(event);
        }else if(el.fireEvent && htmlEvents['on'+eventName]){// IE < 9
            el.fireEvent('on'+event.eventType,event);// can trigger only real event (e.g. 'click')
        }else if(el[eventName]){
            el[eventName]();
        }else if(el['on'+eventName]){
            el['on'+eventName]();
        }
    }
    function addEvent(el,type,handler){
        if(el.addEventListener){
            el.addEventListener(type,handler,false);
        }else if(el.attachEvent && htmlEvents['on'+type]){// IE < 9
            el.attachEvent('on'+type,handler);
        }else{
            el['on'+type]=handler;
        }
    }
    function removeEvent(el,type,handler){
        if(el.removeventListener){
            el.removeEventListener(type,handler,false);
        }else if(el.detachEvent && htmlEvents['on'+type]){// IE < 9
            el.detachEvent('on'+type,handler);
        }else{
            el['on'+type]=null;
        }
    }

    var _body = document.body;
    var customEventFunction = function(){
        alert('triggered custom event');
    }
    // Subscribe
    addEvent(_body,'customEvent',customEventFunction);
    // Trigger
    triggerEvent(_body,'customEvent');
Mr. Raymond Kenneth Petry

Without reading your question I can tell you fireEvent works even on IE11 for e.g. WMP.fireEvent("onmouseup") where WMP is [my] windowsmediaplayer object element....

And worse trouble, if(attachEvent) throws an error instead of taking the false out...sometimes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!