【发布时间】:2009-12-01 06:01:13
【问题描述】:
我想为表格中的数字着色以提高可读性:
- 绿色为阳性 (+00.00);
- 红色表示负 (-00.00) 和;
- 默认情况下为黑色(无符号)
【问题讨论】:
标签: jquery colors numbers readability
我想为表格中的数字着色以提高可读性:
【问题讨论】:
标签: jquery colors numbers readability
来吧:
$(document).ready( function() {
// the following will select all 'td' elements with class "of_number_to_be_evaluated"
// if the TD element has a '-', it will assign a 'red' class, and do the same for green.
$("td.of_number_to_be_evaluated:contains('-')").addClass('red');
$("td.of_number_to_be_evaluated:contains('+')").addClass('green');
}
然后使用 CSS 设置输入元素的样式:
td.red {
color: red;
}
td.green {
color: green;
}
【讨论】:
只有 CSS,没有 javascript 解决方案。 我在这里找到它http://rpbouman.blogspot.ru/2015/04/css-tricks-for-conditional-formatting.html
/* right-align monetary amounts */
td[data-monetary-amount] {
text-align: right;
}
/* make the cells output their value */
td[data-monetary-amount]:after {
content: attr(data-monetary-amount);
}
/* make debit amounts show up in red */
td[data-monetary-amount^="-"]:after {
color: red;
}
<table border="1">
<tr>
<th>Gain</th>
<td data-monetary-amount="$100"></td>
</tr>
<tr>
<th>Losst</th>
<td data-monetary-amount="-$100"></td>
</tr>
</table>
【讨论】:
首先,如果数字是静态的,最好的方法是在服务器端。根据值分配一个类:
<td class="positive">+34</td>
<td class="negative">-33</td>
与:
td { color: black; }
td.positive { color: green; }
td.negative { color: red; }
(或者如果需要,可以更具选择性)。
但如果您必须在客户端上执行此操作,我可能会建议:
$("td").each(function() {
var text = $(this).text();
if (/[+-]?\d+(\.\d+)?/.test(text)) {
var num = parseFloat(text);
if (num < 0) {
$(this).addClass("negative");
} else if (num > 0) {
$(this).addClass("positive");
}
}
});
您可能需要根据要捕获的数字类型(例如 1.2e11 或 3,456)调整正则表达式。
为什么是正则表达式而不仅仅是parseFloat()?因为:
parseFloat("34 widgets");
返回 34。如果这没问题,那么使用它并跳过正则表达式测试。
【讨论】:
"-00.00" (wtf?),您的答案无法设置为“否定”。虽然不确定这个要求是否有意义......
css:
.pos { color:green; }
.neg { color:red; }
标记
<table>
<tr><td>+11.11</td><td>-24.88</td><td>00.00</td></tr>
<tr><td>-11.11</td><td>4.88</td><td>+16.00</td></tr>
</table>
代码
$('td').each(function() {
var val = $(this).text(), n = +val;
if (!isNaN(n) && /^\s*[+-]/.test(val)) {
$(this).addClass(val >= 0 ? 'pos' : 'neg')
}
})
【讨论】:
这里是更完整的解决方案:
<script>
$(document).ready( function() {
// get all the table cells where the class is set to "currency"
$('td.currency').each(function() {
//loop through the values and assign it to a variable
var currency = $(this).html();
//strip the non numeric, negative symbol and decimal point characters
// e.g. Spaces and currency symbols
var val = Number(currency.replace(/[^0-9\.-]+/g,""));
// check the value and assign class as necessary
// (I'm sure this could be done with a switch statement
if(val > 0) {
$(this).addClass('positive');
}
if(val < 0) {
$(this).addClass('negative');
}
})
})
</script>
感谢 Alun Rowe 在http://www.alunr.com/articles/jquery-addclass-to-positive-and-negative-values-on-a-page 提供此代码
【讨论】:
在 td 上设置货币字段类并监听该 td 上的更改事件,然后根据值添加适当的 css 类来更改颜色。
【讨论】: