简体   繁体   中英

addEventListener has no effect when button clicked

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

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? thx

Look in your JavaScript console. You will see that it is complaining that addEventListener is not a function because button is undefined.

Your script runs before the the button has been parsed into the DOM.

Move the script so it is after the button.

Alternatively, wrap the last two lines in a function and addEventListener('load', thatFunction) .


Additionally, there is no bgColor property of style , you want backgroundColor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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