Firefox 5 dispatchEvent not working

爱⌒轻易说出口 提交于 2019-12-20 02:16:04

问题


I have some code that uses dispatchEvent to simulate clicks and the same exact code works fine in Chrome but doesn't work in Firefox. Here's the code:

var evt = document.createEvent("MouseEvents");
evt.initEvent("click",true,true);
jQuery("a:contains(Next)")[0].dispatchEvent(evt);

I'm clicking on a link that loads another page and the page loads fine in Chrome but Firefox does absolutely nothing when I run this code in Firebug or even when I execute it as a bookmarklet. I've also tried the long form of event initializing by setting all the options as shown on the MDC docs but that doesn't do anything. What exactly am I doing wrong here?


回答1:


As your event looks to be a mouse event, you may rather try using a mouse event, like this example :

var oEvt = (document.createEvent)? document.createEvent('MouseEvents') : document.createEventObject();    
       // W3C
        if (oEvt.initMouseEvent) 
            oEvt.initMouseEvent(
                /* type*/            'mouseup',
                /* bubble*/            true,
                /* cancel*/            true,
                /* AbstractView*/     window,
                /* detail */        10,
                /* screenX */        20,
                /* screenY */        30, 
                /* clientX */        40,
                /* clientY */        50,
                /* ctrlKey */        false,
                /* altKey */        false,
                /* shiftKey */        true,
                /* metaKey */        false,
                /* button */        0,
                /* relatedTarget*/    null ) ;
        // MSIE
        else {
                var oEvt = document.createEventObject(); 
                oEvt.detail = 10;
                oEvt.screenX = 20;
                oEvt.screenY = 30;
                oEvt.clientX = 40;
                oEvt.clientY = 50;
                oEvt.ctrlKey = false;
                oEvt.altKey = false;
                oEvt.shiftKey = true;
                oEvt.metaKey = false;
                oEvt.button = 0;
                oEvt.relatedTarget = null;
        }

See W3C Mouse event types

I also wrote a tutorial in French language about firing DOM events ; I guess it's easy to get it translated.




回答2:


This is a bug in Firefox, see this:

https://bugzilla.mozilla.org/show_bug.cgi?id=395917

I don't know of any way to get around it I'm afraid.



来源:https://stackoverflow.com/questions/6474893/firefox-5-dispatchevent-not-working

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