Javascript - 在页面加载时自动点击按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50925683/
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
Javascript - Auto click on a button on page load
提问by Reuben Rodriguez
I am trying to auto click on a button with id btn on page load. This is my snippet.
我试图在页面加载时自动点击一个带有 id btn 的按钮。这是我的片段。
<button id="btn">Click me</button>
<script>
document.getElementById('btn').click();
alert("h")
</script>
How can I give an alert on page load? Pls help. Thanks.
如何在页面加载时发出警报?请帮忙。谢谢。
回答by Nishant Dixit
function test(){
alert("Hi");
}
window.onload = function(){
document.getElementById('btn').click();
var scriptTag = document.createElement("script");
scriptTag.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
<button id="btn" onclick="test()">Click me</button>
回答by Utkanos
Well the alert currently ishappening on page load, because you haven't put it inside an event callback. You presumably meant:
好吧,警报当前正在页面加载时发生,因为您还没有将其放入事件回调中。你大概的意思是:
//wait for DOM ready...
document.addEventListener('DOMContentLoaded', () => {
//...get the button
let btn = document.querySelector('#btn');
//...bind the click event
btn.addEventListener('click', () => { alert('hello'); }, false);
//...trigger the click event on page enter
btn.click();
}, false);
Note also the document ready handler, which waits for the DOM to be ready.
还要注意文档就绪处理程序,它等待 DOM 准备就绪。
回答by Mr. Roshan
Try this:-
试试这个:-
window.onload=function(){
document.getElementById("btn").click();
alert('Page Loaded')
};
function buttonClick(){
alert("button was clicked");
}
<button id="btn" onclick="buttonClick()">Click me</button>
回答by Piyush Modi
If you want to give alert on page load than simply use this -
如果你想在页面加载时发出警报而不是简单地使用这个 -
window.onload = function(){alert("I am loaded")};
But if you want to give an alert after page load also by clicking on button use this -
但是,如果您想在页面加载后也通过单击按钮发出警报,请使用此 -
function autoClick(){
alert("I am loaded and automatically clicked");
}
window.onload = function(){
document.getElementById('autoClickBtn').click();
}
<button id="autoClickBtn" onclick="autoClick()">Click me</button>

