Changing CSS based on the value

前端 未结 4 1426
一整个雨季
一整个雨季 2021-01-22 10:58

I have been asked to implement a small validation on values and if the values are greater or less than 0 i need to change or add/remove the css for the td and i tag

My t

相关标签:
4条回答
  • 2021-01-22 11:25
    var lis=document.querySelectorAll("tr td i");
    for(var i in lis){
        if(parseInt(lis[i].innerHTML)<0){
        lis[i].className+=" fa-level-down";
      }
      else{
            lis[i].className+=" fa-level-up";
      }
    }
    
    0 讨论(0)
  • 2021-01-22 11:29

    Here .slice will remove the % sign in this code and the rest of the code will compare the value and assign or remove class

    var sdlyvar = $('#sdlyvar').text();   
    
    if (sdlyvar.slice(0,-1) < 0){
        $('#sdlyvar').removeClass("fa-level-up");
        $('#sdlyvar').addClass("fa-level-down");
    } else {
        $('#sdlyvar').removeClass("fa-level-down");
        $('#sdlyvar').addClass("fa-level-up");
    }
    
    0 讨论(0)
  • 2021-01-22 11:33

    Your first problem is that you can't compare a string like "-10.95%" with an integer, because of the final % symbol. You have to use parseFloat on tha value:

    var sdlyvar = parseFloat($('#sdlyvar').text());
    

    It will take care of all the non-numeric stuff after the number.

    Then, you'd probably want to remove the opposite class when updating:

    if (sdlyvar < 0){
        $('#sdlyvar').removeClass("fa-level-up").addClass("fa-level-down");
    } else {
        $('#sdlyvar').removeClass("fa-level-down").addClass("fa-level-up");
    }
    

    A few random suggestions:

    1. Make clear what's wrong in your code when posting on StackOverflow
    2. When referring an element more than once with jQuery, consider putting the selection in a variable, like var $sdlyvar = $("sdlyvar");: faster to type and execute.
    3. Save us some whitespaces when posting code :/
    0 讨论(0)
  • 2021-01-22 11:34

    Use JavaScript parseFloat for parsing percentage (http://www.w3schools.com/jsref/jsref_parsefloat.asp).

    var percent = $('#sdlyvar').text();
    var result = parseFloat(percent) / 100.0;
    
    if (result < 0){
        $('#sdlyvar').removeClass("fa-level-up");
        $('#sdlyvar').addClass("fa-level-down")
    } else {
        $('#sdlyvar').removeClass("fa-level-down");
        $('#sdlyvar').addClass("fa-level-up")
    }
    
    0 讨论(0)
提交回复
热议问题