Can I make a table cell have a different background color if the value =< a particular number with jquery or PHP?

前端 未结 5 498
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-28 17:31

I have an HTML table with a lot of numbers.

Is it possible to have a table cell change background color if the value inside that cell (or column) equals or is less than

相关标签:
5条回答
  • 2021-01-28 18:20

    Yes it is easy to do this sort of thing.

    For example, with jQuery, something like this:

    $('table.mytable td').each(function() {
      if (this.textContent <= 3000) {
        $(this).css('background', '#FF0000');
      }
    }
    
    0 讨论(0)
  • 2021-01-28 18:22

    Try this one

    var table = document.getElementById("tableId");
    var row = table.rows[rowIndex];
    var cell = row.cells[cellIndex];
    
    var cellValue = Number(cell.innerHTML);
    
    if (cellValue > 3000)
      cell.style.backgroundColor = "red";
    
    0 讨论(0)
  • 2021-01-28 18:26

    Here is the example //CSS

    .lowerthan100{
     background-color:red;
     color:white;   
    }
    .higherthan100{
     background-color:white;   
     color:red;
    }
    

    //JAVASCRIPT

    $('#mytable td').each(function() {
        if(parseInt($(this).html())>100){
        $(this).addClass("higherthan100");
        }else if (parseInt($(this).html())<100){
        $(this).addClass("lowerthan100");
        }    
     });
    

    //HTML

    <table border="1px" id="mytable">
        <tr><td>99</td><td>101</td></tr>
        <tr><td>200</td><td>50</td></tr>
    </table>
    

    You can populate more class in CSS and else if statements, if you need more conditions.

    Here is the live example http://jsfiddle.net/kayadiker/DL6U2/2/

    0 讨论(0)
  • 2021-01-28 18:28

    Here's an example of how to do it with JS/Jquery

    $("#Yourtable td").each( function() {
         var thisCell = $(this);
         var cellValue = parseInt(thisCell.text());
    
         if (!isNaN(cellValue) && (cellValue <=3000)) {
             thisCell.css("background-color","#FF0000");
          }
      }
     )
    
    0 讨论(0)
  • 2021-01-28 18:29

    You could use code like this:

    $(".colorMe td").each(function() {
        var val = parseInt(this.innerHTML, 10);
        if (val < 3000) {
            this.style.backgroundColor = "#F00000";
        }
    });
    

    See a working example here: http://jsfiddle.net/jfriend00/GAwrB/.

    0 讨论(0)
提交回复
热议问题