Javascript 加载html页面时自动单击按钮

Javascript 加载html页面时自动单击按钮,javascript,html,Javascript,Html,我正在尝试在html页面中创建图像库。我有三个按钮,每个按钮都与图像相连。如果单击按钮1,它将显示与其关联的图片。我已经做到了。但是,我想在页面加载时自动单击第一个按钮。 下面是我的Javascript和HTML代码 var-imgs=[ //数组索引从0开始。。 [], ["http://s9.postimg.org/849kk35kr/bg_play_pause.png"], ["http://s9.postimg.org/u4uiegdmj/image_1.jpg"], ["http:/

我正在尝试在html页面中创建图像库。我有三个按钮,每个按钮都与图像相连。如果单击按钮1,它将显示与其关联的图片。我已经做到了。但是,我想在页面加载时自动单击第一个按钮。 下面是我的Javascript和HTML代码

var-imgs=[
//数组索引从0开始。。
[],
["http://s9.postimg.org/849kk35kr/bg_play_pause.png"],
["http://s9.postimg.org/u4uiegdmj/image_1.jpg"],
["http://s9.postimg.org/3mbv5qewr/image_2.jpg"],
];
功能显示img(imgIndex){
document.getElementById('img1').src=imgs[imgIndex][0];
}

您可以使用以下代码。它将在页面加载时自动单击id为“buttonId”的按钮

<script type="text/javascript">
$(document).ready(function(){
    $("#buttonId").click(); 
});
</script>

$(文档).ready(函数(){
$(“#按钮ID”)。单击();
});

通过这段代码,这最终相当容易实现:

window.onload = function() {
    showImg(1);
}

为什么不直接调用showImg(1)

您可以在Dom加载事件上调用
showImg
函数。如果在
的底部有
script
,甚至可以直接调用函数,但是如果在
中有脚本,则使用Dom加载事件

我还改进了代码

使用图像路径数组。非嵌套数组

var-imgs=[
"http://s9.postimg.org/849kk35kr/bg_play_pause.png",
"http://s9.postimg.org/u4uiegdmj/image_1.jpg",
"http://s9.postimg.org/3mbv5qewr/image_2.jpg"
];
功能显示img(imgIndex){
document.getElementById('img1').src=imgs[imgIndex-1];
}
document.addEventListener('DOMContentLoaded',function(){
showimg1;
},假)

第一
第二
第三

对于javaScript,您可以使用以下命令

window.onload = function(){
  document.getElementById('buttonId').click();
}

加载时使用以下代码调用函数

var e = document.createEvent('MouseEvents');
 e.initMouseEvent('mousedown');
 document.getElementById('buttonId').dispatchEvent(e);

这是jQuery,不是JavaScriptwindow.onload=function(){document.getElementById('buttonId')。单击();}无需等待
load
事件,如果页面上有许多外部资源,则时间太长问题是“页面加载时”,因此答案自然是
window.onload
值得注意的是,对于支持
attachEvent
而不是
addEventListener
@ZathrusWriter的浏览器,我还在答案的底部添加了变通方法