简体   繁体   中英

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

When using .onclick to run a function, it isn't executing it. 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.

You need to bind the onclick handler correctly. 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>

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