如何使用jquery更改表格单元格颜色

如何使用jquery更改表格单元格颜色

问题描述:

I having a html table with inline edit function,when the user edit the td if the value enter by user lower than zero the td color for specific cell would change without refreshing the page.

For example: if cell =< "-1", background-color=#FF0000

there is any way to make this work in reality?

$("#table td").each( function() {
    var thisCell = $(this);
    var cellValue = parseInt(thisCell.text());        
    if (!isNaN(cellValue) && (cellValue >=0)) {
        thisCell.css("background-color","#FF0000");
    }
});

我有一个带有内联编辑功能的html表,当用户编辑td时,如果用户输入的值低于 零,特定单元格的td颜色会在不刷新页面的情况下发生变化。 p>

例如:if cell =&lt; “-1”, background-color =#FF0000 code> p>

有什么方法可以让这项工作变为现实吗? p>

  $(“#table td”)。each(function(){
 var thisCell = $(this); 
 var cellValue = parseInt(thisCell.text()); 
 if(!isNaN(  cellValue)&amp;&amp;(cellValue&gt; = 0)){
 thisCell.css(“background-color”,“#FF0000”); 
} 
}); 
  code>  pre  > 
  div>

Just iterate every cell, parse its content and set the background color:

function updateColors () {
    $("td").css("background-color", "white");
    $("td").each (function () {
       var $cCell = $(this);
       if (Number ($cCell.text()) <= -1) {
          $cCell.css("background-color", "#FF0000");
       }
    });
}

updateColors();

// http://*.com/a/7804973/1420197    
var allCells = document.querySelectorAll("td");
for (var i = 0; i < allCells.length; ++i) {
    allCells[i].addEventListener("DOMCharacterDataModified", function () {
        console.log(this.innerText);
        updateColors();
    });
}

Demo

JSFIDDLE

Give an ID to your cell, like <td id='cellID'>34</td> then do this in jquery:

var _cellValue = $("#cellID").html();
_cellValue = parseInt(_cellValue);
if (_cellValue=<-1){
  $("#cellID").css("background-color","#FF0000");
}

Briefly tested, hope this helps:

var colors = {
    black: {
        num: 1,
        hex: '000'
    },
    red: {
        num: 2,
        hex: 'f00'
    },
    grey: {
        num: 3,
        hex: '333'
    }
};

function getColor(num) {
    var color = '#fff'; // default
    $.each(colors, function(index, obj) {
        if (parseInt(obj.num)===parseInt(num)) {
            color = '#'+obj.hex;
        }
    });
    return color;
}

$(document).on('keyup', '#mytable td', function() {
    var current = $(this).text();
    if (current.length > 0 && !isNaN(current)) {
        $(this).css('background-color', getColor(current));
    }
    else {
        // NaN, Set default color, handle errors, etc...
        $(this).css('background-color', '#fff');
    }
});