javascript 如果值 =< 使用 jquery 或 PHP 的特定数字,我可以使表格单元格具有不同的背景颜色吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7425719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I make a table cell have a different background color if the value =< a particular number with jquery or PHP?
提问by Erik
I have an HTML table with a lot of numbers.
我有一个包含很多数字的 HTML 表格。
Is it possible to have a table cell change background color if the value inside that cell (or column) equals or is less than a particular number?
如果该单元格(或列)内的值等于或小于特定数字,是否可以让表格单元格更改背景颜色?
For example: if cell =< "3000", background-color=#FF0000
例如:如果单元格==“3000”,则背景颜色=#FF0000
Is there a way to make this work in reality?
有没有办法使这项工作在现实中发挥作用?
Erik
埃里克
回答by JohnFx
Here's an example of how to do it with JS/Jquery
这是一个如何使用 JS/Jquery 进行操作的示例
$("#Yourtable td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue <=3000)) {
thisCell.css("background-color","#FF0000");
}
}
)
回答by jfriend00
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/.
在此处查看一个工作示例:http: //jsfiddle.net/jfriend00/GAwrB/。
回答by kaya
Here is the example //CSS
这是示例 //CSS
.lowerthan100{
background-color:red;
color:white;
}
.higherthan100{
background-color:white;
color:red;
}
//JAVASCRIPT
//Java脚本
$('#mytable td').each(function() {
if(parseInt($(this).html())>100){
$(this).addClass("higherthan100");
}else if (parseInt($(this).html())<100){
$(this).addClass("lowerthan100");
}
});
//HTML
//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.
如果需要更多条件,您可以class
在 CSS 和else if
语句中填充更多内容。
Here is the live example http://jsfiddle.net/kayadiker/DL6U2/2/
回答by Gregory Nozik
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";
回答by thomasrutter
Yes it is easy to do this sort of thing.
是的,做这种事情很容易。
For example, with jQuery, something like this:
例如,使用 jQuery,是这样的:
$('table.mytable td').each(function() {
if (this.textContent <= 3000) {
$(this).css('background', '#FF0000');
}
}