是否可以通过JavaScript触发链接(或任何元素)的点击事件? [英] Is it possible to trigger a link's (or any element's) click event through JavaScript?
本文介绍了是否可以通过JavaScript触发链接(或任何元素)的点击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一些需要触发点击
事件的JavaScript代码。在Internet Explorer中我可以这样做
I'm writing some JavaScript code that needs to fire the click
event for a link. In Internet Explorer I can do this
var button = document.getElementById('myButton');
button.click();
但这在Firefox中不起作用,我假设任何其他浏览器。在Firefox中,我已经完成了这个
But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this
var button = document.getElementById('myButton');
window.location = button.href;
我觉得这不是最好的方法。有没有更好的方法来触发点击
事件?无论元素类型或浏览器如何,最好是有效的东西。
I feel like this is not the best way to do this. Is there a better way to trigger a click
event? Preferably something that works regardless of the type of element or the browser.
推荐答案
http://jehiah.cz/archive/firing-javascript-events-properly
function fireEvent(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
}
这篇关于是否可以通过JavaScript触发链接(或任何元素)的点击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文