簡體   English   中英

基於Java單元格內容的表格格式

[英]Table formatting based on cell content in Javascript

我有一個表格,在最左邊的一列中有文本,在所有其他列中有數字。 如何根據單元格中的編號為單元格着色? 我想將background-color =“ red”設置為負數,並忽略其中包含文本的列,也忽略其中包含正數的單元格。

以下是我從另一個問題中選取並修改了一點的代碼,但是它似乎不起作用。

var allTableCells = document.getElementsByTagName("td");
for(var i = 0, max = allTableCells.length; i < max; i++) {
    var node = allTableCells[i];
    var currentVal = node.childNodes[0].nodeValue; 
    if(currentVal.toFixed){
        if (currentVal <0)
            node.style.backgroundColor = "red"; // -ive number
    } else{
        // do nothing, the cell has text
    }
}

您應該解析數字:

var allTableCells = document.getElementsByTagName("td");
for(var i = 0, max = allTableCells.length; i < max; i++) {
    var node = allTableCells[i];
    var currentVal = parseFloat(node.childNodes[0].nodeValue); 
    if(currentVal!=NaN){
        if (currentVal <0)
            node.style.backgroundColor = "red";
    } 
}

或更適合jQuery和CSS:

腳本:

$("td").filter(function(c){
    var num=parseFloat(this.innerText);
    return num!=NaN && num < 0;
}).addClass("neg");

要么

$("td:contains('-')").addClass("neg");

CSS:

.neg{
    background-color: red;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM