Simulate a click on a link with JavaScript
I need to simulate a click on a开发者_运维百科 link using JavaScript. Could anybody tell me how it can be achieved? It should work in FireFox and IE.
Thanks in advance.
As mentioned by others, you can use click
method for IE. For Firefox, have a look at element.dispatchEvent. See the example in the documentation.
var el = document.getElementById('link');
// Firefox
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
el.dispatchEvent(event);
}
// IE
else if (el.click) {
el.click();
}
example
this should do the trick
document.getElementById('yourLink').click();
document.getElementById('mylink').click()
精彩评论