如果表格单元格值为> = 0,那么它如何使表格单元格值变为红色?顺便提一下,这个值来自数据库。
答案 0 :(得分:4)
编辑后使用vanilla JS: (Here is a working fiddle)(In this one the entire row gets colored red)
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
}
}
};
如果您只需要支持现代浏览器,我认为this solution更漂亮:
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
}
}
}