[英]I want to hide the image when clicked. Calling function when element.onclick not working
var image = document.getElementById("image");
function hide(el){
el.hidden = true;
}
image.onclick = hide(image);
我已经无数次地研究了这部分,但是我还不够聪明,无法理解为什么它不起作用。 谢谢你们的帮助。
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Chore Door!</title>
<link href="./style.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Work+Sans" rel="stylesheet" type="text/css">
</head>
<body>
<div id="image"><img src="https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/closed_door.svg" id="image></div>
<script src="script.js"></script>
</body>
</html>
您的函数在页面加载时被调用并执行。 在匿名函数内部调用该函数。
请注意:您没有任何id=image
元素。
var image = document.getElementById("image"); function hide(el){ el.hidden = true; } image.onclick = function(){ hide(image) };
<div id="image"><img src="https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/closed_door.svg" id="image"></div>
以下演示可能会帮助您清除疑问:
var image = document.getElementById("image"); function hide(){ image.hidden = true; } image.onclick = hide; // notice there is no () after the function name, here the function will not be executed on page load
<div id="image"><img src="https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/closed_door.svg" id="image"></div>
document.getElementById("image").addEventListener('click', function() {
this.hidden = true;
}
当我查看您的HTML时,没有ID为“ image”的图像,因此document.getElementById("image")
调用不会返回任何元素。
您可能要使用getElementsByTagName("image")
代替,但请注意,这是一个元素数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.