我想在表格中为数字着色以提高可读性:
- 绿色为正 (+00.00);
- 红色表示负数 (-00.00) 和;
- 默认情况下为黑色(无符号)
我想在表格中为数字着色以提高可读性:
给你:
$(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)调整正则表达式。
为什么是正则表达式而不是 just parseFloat()
?因为:
parseFloat("34 widgets");
返回 34。如果这没问题,那么使用它并跳过正则表达式测试。
的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 类来更改颜色。