简体   繁体   English

单击按钮时,addEventListener无效

[英]addEventListener has no effect when button clicked

HTML HTML

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<script type="text/javascript" src="MouseEvent.js"></script>
<script type="text/javascript" ></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<button id="btn" type="button">Click Me!</button>
</body>
</html>  

Javascript 使用Javascript

var handleclick = function(event)
{
document.body.style.bgColor="red";
};

var button = document.getElementById("btn");
button.addEventListener('click',handleclick,false);

For some reason when "btn" is clicked the background color does not change,what is going wrong here? 出于某种原因,当点击“btn”时,背景颜色不会改变,这里出了什么问题? thx 谢谢

Look in your JavaScript console. 查看您的JavaScript控制台。 You will see that it is complaining that addEventListener is not a function because button is undefined. 您将看到它抱怨addEventListener不是函数,因为button未定义。

Your script runs before the the button has been parsed into the DOM. 您的脚本在按钮被解析到DOM之前运行。

Move the script so it is after the button. 移动脚本使其位于按钮之后。

Alternatively, wrap the last two lines in a function and addEventListener('load', thatFunction) . 或者,将最后两行包装在函数和addEventListener('load', thatFunction)


Additionally, there is no bgColor property of style , you want backgroundColor . 此外,没有style bgColor属性,您需要backgroundColor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM