admin管理员组

文章数量:1425999

The following JS code works on Safari properly :

var a = $('.shell a')[0];
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
a.dispatchEvent(evObj);

However, this line

evObj.initMouseEvent('click', true, true, window);

gives me the following error in Firefox:

TypeError: Not enough arguments to MouseEvent.initMouseEvent.

What should I use for multi-browser patibility?

The following JS code works on Safari properly :

var a = $('.shell a')[0];
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('click', true, true, window);
a.dispatchEvent(evObj);

However, this line

evObj.initMouseEvent('click', true, true, window);

gives me the following error in Firefox:

TypeError: Not enough arguments to MouseEvent.initMouseEvent.

What should I use for multi-browser patibility?

Share Improve this question edited Nov 5, 2014 at 17:11 Jeff B 9,01220 gold badges67 silver badges144 bronze badges asked Nov 5, 2014 at 16:02 Arvind KushwahaArvind Kushwaha 8192 gold badges11 silver badges19 bronze badges 3
  • That's the old way. The new way is much simpler: evObj = new Event('click'); -- All browsers? Goodluck with that. click is simple though. Just do domElement.click(). – Rudie Commented Nov 5, 2014 at 16:06
  • @Rudie Do you mean jQueryElement.click()? – David Knipe Commented Nov 5, 2014 at 16:35
  • No, I mean the native domElement.click(). Try it in the console: document.querySelector('a').click() – Rudie Commented Nov 5, 2014 at 16:56
Add a ment  | 

1 Answer 1

Reset to default 4

As you can see on MDN's initEvent page, using events like that is deprecated. "Use event constructors instead":

https://developer.mozilla/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

In your case:

var evObj = new Event('click');
a.dispatchEvent(evObj);

But click events are much simpler! Native DOM has a click() method for all elements, so you can do this:

a.click();

That's it.

If you want to trigger custom events or events like mouseover, you can still use the (new) event dispatch system: new Event('mouseover') etc

本文标签: javascriptnot enough arguments to mouseEventinitMouseEventStack Overflow