在 Javascript 中使用 setTimeout 模拟点击
如何使用 setTimeout 模拟点击事件?像这样的东西:
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
目前,您的代码立即调用
click()
并将返回值传递给setTimeout
。相反,您希望将函数引用传递给setTimeout
:编辑: 正如 @ThiefMaster 指出的,您还希望将函数传递给
onload
;即使它看起来可能有效,但它不会做它真正应该做的事情。Currently your code calls
click()
immediately and passes the return value tosetTimeout
. You instead want to pass a function reference tosetTimeout
: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()
在脚本首次运行时进行评估。您需要将其变成一个函数并将其作为第一个参数传递。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.