简体   繁体   中英

Change image source on click javascript

So, I have an upvote image, when that upvote image is clicked, it should change to downvote image. So, in my img/ folder in my directory, I have these two upvote and downvote images. So, basically, when the upvote image is clicked, it should change to downvote image, by changing source (src), which I tried to achieve using Javascript.

However, what's happening is, when the upvote button is clicked, it's displaying both the upvote button and the downvote button at the same time. It should only display the downvote button on the click of the upvote button. Any clue on why this is occurring? Thanks a lot for the help!

 function changetextUpvote() { var textUpvoteImg = document.getElementById("textUpvoteImg"); if (textUpvoteImg.src.match("downvote")) { textUpvoteImg.src = "img/upvote.png"; textUpvoteImg.alt = "Voted up"; // for debugging } else { textUpvoteImg.src = "img/downvote.png"; textUpvoteImg.alt = "Voted down"; // for debugging } }
 <img class="textupvote" id="textUpvoteImg" src="img/upvote.png" alt="upvote" onclick="changetextUpvote()" style="width: 100px; margin-bottom: 28px; cursor: pointer">

I only used your code with <script> tag and it is working.

<script>
function changetextUpvote() {
  var textUpvoteImg = document.getElementById("textUpvoteImg");
  if (textUpvoteImg.src.match("downvote")) {
    textUpvoteImg.src = "img/upvote.png";
  } else {
    textUpvoteImg.src = "img/downvote.png";
  }
}
</script>

<img class="textupvote" id="textUpvoteImg" src="img/upvote.png" alt="upvote" onclick="changetextUpvote()" style="width: 100px; margin-bottom: 28px; cursor: pointer">

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