如何自动单击div中的链接

时间:2019-07-06 18:45:58

标签: javascript dom

我试图在短暂的延迟后自动单击div中的第一个链接,但是我的代码无法正常工作。怎么了?

//HTML
<div id="main">
<p>The first paragraph.</p>
<a href="https://www.google.com" target="_blank">Google link</a>
<p>The second paragraph.</p>
</div>

//Just checking that I selected the link
<p id="demo"></p>

<script>
var x = document.getElementById("main");
var y = x.getElementsByTagName("a");

//Here's just checking I got the link
document.getElementById("demo").innerHTML = 
'The first link (index 0) inside "main" is: ' + y[0].href;

//Here's the timer
    window.setTimeout("autoClick()", 2000);

//And this is what isn't working...
function autoClick() {
var linkPage = y[0];
window.location.href = linkPage;
}
</script>

我显然缺少了一些明显的东西,因为自动点击无法正常工作,但看不到它可以看-有人可以看到我犯的基本错误吗?

2 个答案:

答案 0 :(得分:0)

window.location.href = linkPage.getAttribute('href')

setTimeout(autoClick, 2000)

答案 1 :(得分:0)

您必须使用getAttribute('href')才能检索href值。您的行应显示为:

window.location.href = linkPage.getAttribute('href');

完整的代码应该看起来像(格式和稍有改进):

<div id="main">
    <p>The first paragraph.</p>
    <a href="https://www.google.com" target="_blank">Google link</a>
    <p>The second paragraph.</p>
</div>

<p id="demo"></p>

<script>

    let x = document.getElementById("main");
    let y = x.getElementsByTagName("a");

    // Test code...
    document.getElementById("demo").innerHTML = 'The first link (index 0) inside "main" is: ' + y[0].href;

    // Auto click after 2 seconds...
    window.setTimeout(autoClick, 2000);

    function autoClick() {
        window.location.href = y[0].getAttribute('href');
    }

</script>

注释

  • 使用let代替var
  • 调用autoClick函数时不需要括号或引号
  • 无需创建变量linkPage,只需使用y[0]