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

问题描述 投票:-3回答:2

使用.onclick运行函数时,它不执行它。我做错了什么吗?

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

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

当我点击对象时,我期待image1(成功显示)更改为image2。

javascript html onclick
2个回答
0
投票

您需要正确绑定onclick处理程序。这将是一种方法:

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

0
投票

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

  object1.onclick = () => {
    object1.src = image2Path;
  }
<body>
  <img id='object1' src="image1.svg">
</body>
© www.soinside.com 2019 - 2024. All rights reserved.