开发者

Firefox 5 dispatchEvent in Firefox

I have some code that uses dispatchEvent to simulate clicks and开发者_Python百科 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜