我想在单击时隐藏图像。当element.onclick不起作用时调用函数

时间:2019-07-16 08:28:41

标签: javascript

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>

3 个答案:

答案 0 :(得分:3)

您的函数在页面加载时被调用并执行。在匿名函数内部调用该函数。

请注意:您的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>

答案 1 :(得分:0)

document.getElementById("image").addEventListener('click', function() {
  this.hidden = true;
}

答案 2 :(得分:0)

当我查看您的HTML时,没有ID为“ image”的图像,因此在document.getElementById("image")调用中不会返回任何元素。

您可能想改用getElementsByTagName("image"),但请注意,这是一个元素数组。