简体   繁体   中英

How do I track changes to my Javascript?

I am have text that when you click it, the background-color turns green, and if you click it again it turns red and then one more click it turns back to white. I have successfully linked my javascript to change the color to green but I can't figure out how to track the changes to javascript to recognize that it is green, and then to change it to red.

What I have is something like this:

<script type="text/javascript">
function change_color($id){

    var link = document.getElementById('link-'+$id);

    var color = link.style.backgroundColor;
    if (color == "green"){
    link.style.backgroundColor="red";
    }if (color == "red"){
    link.style.backgroundColor="white";
    }if (color == "white"){
    link.style.backgroundColor="green";
    }else{
    link.style.backgroundColor="green";
    }

}

</script>

When I run the program it is only using the else statement I believe. How can I track the current backgroundColor in order to activate the above if statements?

If the color is green, you set it to red. Then the next condition checks for red (which is now true) and updates the color again.

Consider using a switch statement instead of the if / else statements.

If you want to check multiple conditions but only run one of them , you need to use else if for all conditions after the first one:

if (color == "green"){
    link.style.backgroundColor="red";
}else if (color == "red"){
    link.style.backgroundColor="white";
}else if (color == "white"){
    link.style.backgroundColor="green";
}else{
    link.style.backgroundColor="green";
}

Either use if..else if..else between your if 's or use a switch-case instead:

var color = link.style.backgroundColor;
var newColor = "green";
switch (color) {
    case "green":
    {
        newColor="red";
        break;
    }

    case "red":
    {
        newColor="white";
        break;
    }

    case "white":
    {
        newColor = "green";
        break;
    }

    default:
    {
        break;
    }
}

link.style.backgroundColor = newColor;

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