JavaScript Cross-Browser Click on a HTML DOM Element

感情迁移 提交于 2019-12-12 12:34:01

问题


Is there a vanilla JavaScript cross-browser function available that is able to trigger a click event on a HTML DOM element (including non-form elements like a div)?


回答1:


Most who go down this path either end up developing their own event managment system (which isn't that hard but is annoying) or work within the available capabilities.

If all browsers supported a single model, (say the W3C event model), life would be sweet. But they don't. And not only that, some browsers refuse to respond to programmatic events the same way as "real" events. e.g. dispatching a click event using displatchEvent on a link in Firefox will not cause the browser to follow the link (but will trigger the onclick listener if there is one). Most other browsers will follow the link.

IE didn't support dispatchEvent up to version 8 (perhaps 9 does), it has fireEvent which is similar but different.

HTML5 (which is not a standard yet, maybe it never will be) has introduced a click method for the HTMLElement interface, however it's not fully implemented yet and can't be relied upon. It can likely be used for environments where you know or can control the browser versions that will be using the page.

You can also just call the element's onclick property if a listener has been assigned to the property or inline, but of course that's not like a real event.

Useful post on dispatchEvent on clj.




回答2:


var target = document;//<--(insert your target here);
if(document.createEvent){
  var clickEvent = document.createEvent("MouseEvents");
  clickEvent.initMouseEvent("click", true, true, window, 
    0, 0, 0, 0, 0, false, false, false, 0, null);
  target.dispatchEvent(clickEvent);
}
else{
  target.fireEvent("onclick");
}

Taken from the MDC event.initMouseEvent reference and this SO question.

jsFiddle that you can test on different browsers.




回答3:


Found this elusive function on Mozilla documentation: https://developer.mozilla.org/En/DOM/Document.createEvent, and here too: http://javascript.gakaa.com/document-createevent-4-0-5-.aspx

function performClick(node) {
    var evt = document.createEvent("MouseEvents");
    evt.initEvent("mousedown", true, true);
    document.getElementById("myElement").dispatchEvent(evt);
}



回答4:


Given:

<input type="button" id="myButton" onclick="alert('hello world');"/>

The following would invoke the hello world prompt:

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


来源:https://stackoverflow.com/questions/6838661/javascript-cross-browser-click-on-a-html-dom-element

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