-1

如果它> = 0,我如何使表格单元格值然后它使表格行背景颜色变为红色?顺便说一下,值是从数据库中获取的。

4

1 回答 1

4

使用香草JS,编辑后:(这是一个工作小提琴)在这个中,整行都变成红色

window.onload = function(){ // After all the contents has loaded
    var cells=document.getElementsByTagName("td"); //select all the table cell tags
    for(var i=0;i<cells.length;i++){  //iterate through each of them
       //check if content is more than 0
       if(parseFloat(cells[i].textContent || cells[i].innerText)>=0){ 
           cells[i].style.backgroundColor="red"; //change background to red
       }
    }
};

如果只需要支持现代浏览器,我觉得这个方案比较漂亮:

window.addEventListener("DOMContentLoaded", function(e) {
    document.getElementsByTagName("td").filter(function(elem){
        return parseFloat(elem.textContent) >= 0;
    }).forEach(function(elem){
        elem.style.backgroundColor="red";
    });
 }, false);

旧内容,jquery解决方案:


$(function(){  //after the dom is loaded
    $("td").each(function() {
        if(parseFloat($(this).text()) >= 0){ //for every element whose text's float value is less than 0
           $(this).css("background-color","red"); //change the background color to red
        }
    }  
}
于 2013-04-01T18:27:02.263 回答