在java脚本中无法在页面加载时显示两个警报按钮

moh*_*abu 0 html javascript jquery

我正在尝试编写一个代码,在加载页面时显示两个警报按钮.但是,我只能加载其中一个警报按钮(init2),即init1弹出窗口没有出现.下面附上我的代码.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Insert title here</title>
<script>
 // fname will be executed when the <body> tag loads
 function addOnLoad(fname){ 
    // Define this function

    window.onload=fname;
}

// init1 and init2 should be alerted when the body tag loads
addOnLoad(function (){alert('init1!'); });
addOnLoad(function (){ alert('init2!'); });
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

输出我得到:

在此输入图像描述

我不明白为什么init1的警报按钮没有打印的原因.我希望它们都打印出来.任何建议都会非常有用.

Tha*_*yne 5

您的addOnLoad函数正在通过设置替换事件处理程序window.onLoad,而不是添加新的处理程序.如果要添加其他处理程序,则需要使用

window.addEventListener('load', fname);
Run Code Online (Sandbox Code Playgroud)

另请注意,浏览器一次只会显示一个警报,因此警报将按顺序显示,而不是同时显示.