简体   繁体   English

单击href链接的Javascript

[英]Javascript to click on href link

I got this code after searching around on stack overflow and it should work, but for some reason I am getting an error. 我在堆栈溢出中搜索后得到了这段代码,它应该可以工作,但是由于某种原因,我遇到了错误。 I am trying to write JS that simulates a user clicking on a specific href link that has a specific ID. 我正在尝试编写模拟用户单击具有特定ID的特定href链接的JS。

This needs to work in all the major browsers (chrome, FF, IE, Safari) 这需要在所有主要浏览器(chrome,FF,IE,Safari)中都可以使用

here is the code: 这是代码:

HTML: HTML:

<a id="clickhere" href="http://link.com">Need to simulate user clicking on this link</a>

JS: JS:

fireOnclick();
function fireOnclick() {
var target=document.getElementById("clickhere");
if(document.dispatchEvent) { // W3C
    var oEvent = document.createEvent( "MouseEvents" );
    oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, target[0]);
    target[0].dispatchEvent( oEvent );
    }
else if(document.fireEvent) { // IE
    target[0].fireEvent("onclick");
    }    
}

Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

You need to remove the [0] from your target[0] references. 您需要从target[0]引用中删除target[0] getElementById returns an element, not an array of elements. getElementById返回一个元素,而不是元素数组。 I tested in Chrome and it worked fine. 我在Chrome中进行了测试,效果很好。

http://jsfiddle.net/mendesjuan/vCVbA/1/ http://jsfiddle.net/mendesjuan/vCVbA/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM