最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Simulate click with setTimeout in Javascript - Stack Overflow

programmeradmin6浏览0评论

How would I simulate a click event with setTimeout? Something like:

<script>
    window.onload=setTimeout(document.getElementById('mk1').click(),1000);
</script>

<a id="mk1" href="some url">click me</a>

How would I simulate a click event with setTimeout? Something like:

<script>
    window.onload=setTimeout(document.getElementById('mk1').click(),1000);
</script>

<a id="mk1" href="some url">click me</a>
Share Improve this question edited May 17, 2011 at 14:03 Jeremy 22.4k4 gold badges70 silver badges81 bronze badges asked May 17, 2011 at 13:49 cj333cj333 2,60921 gold badges70 silver badges111 bronze badges 1
  • 1 If you really want to simulate a click, then casablanca has the right answer. If you just want to redirect the page to a different url, then assign a value to window.location – Allen Rice Commented May 17, 2011 at 13:56
Add a ment  | 

2 Answers 2

Reset to default 13

Currently your code calls click() immediately and passes the return value to setTimeout. You instead want to pass a function reference to setTimeout:

window.onload = function() {
  setTimeout(function() {
    document.getElementById('mk1').click();
  }, 1000);
};

Edit: As @ThiefMaster points out, you also want to pass a function to onload; even though it might seem to work otherwise, it wouldn't do what it really should be doing.

document.getElementById('mk1').click() is evaluating when the script first runs. You need to make it into a function and pass that as the first parameter.

发布评论

评论列表(0)

  1. 暂无评论