简体   繁体   English

使用 javascript .onclick 函数的正确方法是什么?

[英]What is the correct way to use the javascript .onclick function?

When using .onclick to run a function, it isn't executing it.当使用 .onclick 运行一个函数时,它并没有执行它。 Have I done something wrong?我做错了什么吗?

<script>
  const object1 = document.getElementById('object1');
  const image2Path = "image2.svg";

  object1.onclick = () => {
    object1.src = image2Path;
  }
</script>
<body>
  <img id='object1' src="image1.svg">
</body>

I'm expecting image1 (which shows up successfully) to change to image2 when I click on the object.当我单击对象时,我期待 image1(成功显示)更改为 image2。

You need to bind the onclick handler correctly.您需要正确绑定 onclick 处理程序。 This would be a way to do it:这将是一种方法:

<script>
  function toogle()
  {
     const object1 = document.getElementById('object1');
     const image2Path = "image2.svg";

     object1.src = image2Path;
  }
</script>
<body>
  <img id='object1' src="image1.svg" onclick="toggle();">
</body>

 const object1 = document.getElementById('object1'); const image2Path = "image2.svg"; object1.onclick = () => { object1.src = image2Path; }
 <body> <img id='object1' src="image1.svg"> </body>

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

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