我写了一个小程序,使用addEventListener()单击按钮时弹出警报。 PFB下面的代码:addEventListener()没有响应
HTML文件
<html>
<head>
<title>name alert</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<input id="p" type="button" value="alert">
</body>
</html>
JavaScript文件
document.getElementById("p").addEventListener("click",greet,true);
function greet(){
alert("hello there !");
}
我没有得到一个弹出屏幕这样这两个文件都在同一个文件夹BTW。
你的代码的工作:https://jsfiddle.net/c0sLjy2t/。也许JavaScript的来源是错误的?! –
在控制台中是否出现错误?脚本标记在html之前? – DoctorMick
检查控制台,查看错误。该脚本将在构造DOM之前执行并且在其中出现“p”元素,因此'getElementById'调用只返回'null'。 – raina77ow