如何使用 javascript 将 click() 应用于标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7838578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:30:12  来源:igfitidea点击:

how to apply click() to a tag using javascript

javascriptclick

提问by bammab

I am trying to emulate a click on a basic link that appears like this with no id or class.

我正在尝试模拟对基本链接的点击,该链接看起来像这样,没有 id 或 class。

<a href="http://www.myebsite.com/service/playnow">Click to Start</a>

I have the following code but when i load the page to no click action is performed. What am I doing wrong?

我有以下代码,但是当我加载页面时没有执行点击操作。我究竟做错了什么?

    var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
    if(a){
        a.click();
    }

回答by Mike Christensen

Why your tag doesn't have an ID is strange, but I'll assume for some reason you can't control that. I don't think you can emulate a click through a "click" method, so perhaps try something like:

为什么你的标签没有 ID 很奇怪,但我假设出于某种原因你无法控制。我认为您无法通过“点击”方法模拟点击,因此可以尝试以下操作:

var a = document.evaluate( '//a[contains(@href, "playnow")]' ,document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
if(a){
   window.location.href = a.href;
}

回答by JaredPar

The easiest way is to add an id to the anchor tag and then invoke the clickfunction on the DOM element

最简单的方法是在锚标签中添加一个id,然后调用clickDOM元素上的函数

HTML:

HTML:

<a id="theAnchor" href="http://www.myebsite.com/service/playnow">Click to Start</a>

JavaScript:

JavaScript:

document.getElementById('theAnchor').click();