简体   繁体   中英

Javascript if/else statement using image src as condition

I have a voting script with an arrow system (upvotes and downvotes).If user clicks upvote, the arrow changes to the green arrow, meaning vote registered. If they click again, I want the arrow to revert back to the original image. However, using my code, it changes the image on the first like, but doesn't revert back on a second click.

if (like.src = 'vote_triangle.png') {
  like.src = 'vote_triangle_like.png';
} else {
  like.src = 'vote_triangle.png';
}

I know it's a very old thread, but I would like to add my findings here for future reference.

I found the following code wasn't working:

function swapImage() {
    var element = document.getElementById("myImage");        

    if (element.src == "image1.png") {
        element.src = "image2.png";
    } else {
        element.src = "image1.png"
    }
}

Showing alerts containing the element.src taught me it contained the full path to the image in my local machine. Thus, the if statement had been always evaluated to false.

To fix that in a logical manner, what I did was get the attribute of the element, as the following code shows.

function swapImage() {
    var element = document.getElementById("myImage");

    if (element.getAttribute("src") == "image1.png") {
        element.src = "image2.png";
    } else {
        element.src = "image1.png";
    }
}

By using the function getAttribute("attributeName") , I was able to retrieve the path contained in the src relatively to the project directory.

Use a more lenient if statement like:

if (like.src.indexOf('vote_triangle.png')!=-1) {
  like.src = 'vote_triangle_like.png';
} else {
  like.src = 'vote_triangle.png';
}

I would suggest, instead of using img soruce as conditional statement, use a global variable, change its state once the upvote is clicked by say +1 and for downvotes -1.

//when 0, show upvote image, make it a global by declaring before any function
var UpVote = 0;

//when upvote clicked, when greater than 0, show down vote img
UpVote = UpVote +1 ;

//conditional logic for img source
if(UpVote > 0){
  like.src = 'vote_triangle.png';
}
else{
  like.src = 'vote_triangle_like.png';
}

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