简体   繁体   中英

How do I make it so when I click a button my image changes?

I tried to create a function where when the button is clicked the source of the image changed, but it didn't work.

<img
   class="bowgart"
   id="bowgart"
   src="C:\Users\jbrir\Documents\BowgartWebsite2\images\bowgart.png"
   alt="Bowgart"
/>
<script>
   function imgOpen() {
      document.getElementById("bowgart").src = "C:UsersjbrirDocumentsBowgartWebsite2imagesBowgart_open.jpeg";
   }
</script>

The src needs to be a valid URL. You're missing the file: URL scheme and all the / delimiters in the pathname.

function imgOpen() {
  document.getElementById("bowgart").src =
    "file:///C:/Users/jbrir/Documents/Bowgart/Website2/images/Bowgart_open.jpeg";
}

I recommend using this code:

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>

The way how this code works is that when you click the button it changes the source of the image(you do have to have both images) and applies that to the image. And if that was confusing to you then here is a simpler way of saying that: if the image was off and you click the 'on' button it will change to image to on else it does not do anything and the same if it was on. And this is just an example so apply this to your images.

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