简体   繁体   中英

JavaScript if statement changing text color

This is my first post on these forums. I'm trying to create a table that calls its numbers from a VoIP test result on a program that I run in the HTML. currently, im trying to make the result table look "pretty" by if the VoIP Jitter is recorded 1 or above it will change the text color to red and vise versa to green.

function testFinished(vJit) {
  voipcolor(vJit);
  document.getElementById("aftert").innerHTML='<table class="tableRes" id="tableRes"><style>table {border:1px solid black; margin-left:auto; margin-right:auto;} th, td{border:1px solid black;}</style><thead><thead><tr><th colspan="2">VoIP Test</th></tr></thead><Tr><td>Jitter</td><td>' + vJit + 'ms</td></tr></table>';
}

I have also created the an if statement but for some reason, I keep getting errors for the "unexpected token if":

function voipcolor(vJit)
    if (vJit < 1) {
        let vJit = '<p style="color:green;">' + vJit + '</p>'
    }else if (vJit >= 1) {
        let vJit = '<p style="color:red;">' + vJit + '</p>'
    }
}

there is more to the table but because i am asking about the colors i figured i would just refrence 2 cells instead of 10 or more.

  1. what is causing the error with the if statement?
  2. what is the proper way to insert the color change?

so I realize I need a return statement and tried adding that to the function also I beleave I edit the else issue that @Taplar was mentioning.

function voipcolor(vJit) {
  if (vJit < 1) {
    return voipcolor.style.color = "green"    
  }else{
    return voipcolor.style.color = "red";
  }
}

but nothing is happening. I believe I need to call the voipcolor(vJit) but im not sure how.

I'm not sure how all your HTML/CSS is defined, but can you make your code look something like this?

        if (vJit < 1){
           p.style.color = "green";}
        if (rating >= 1){
           p.style.color = "red";}

Playing with this might help too: https://www.w3schools.com/js/js_htmldom_css.asp

so I ended up asking my mentor/teacher/boss... thing... person, for some help. I was not calling the function with the if statement. so what I did was called the function from the table replacing + vJit + with function voipcolor(vJit) then in the voipcolor function instead of return voipcolor.style.color = "green" I used return '<span style="color: green">' + vJit + '</span>' Because I am calling the function the whole function runs in order. when I use the return statement, the function stops running at the return statement. there are other ways to make this work and explaining this is more for my understanding than anything else. I do hope people will learn from this and understand the innerHTML attribute as I have.

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