2012-10-30 50 views
0

我想要的颜色,以根据病情红色负值颜色在TD值的情况下,我现在所做的是这样的:想使用jQuery

$('td.numeric:contains('-')").addClass("negative") 

以上具有类名称的数字,如果代码中找到TD值包含' - ',它将类'负'应用于该td。

我的问题是,如果我应用数字类例如日期值也包含' - '作为分隔符,并使日期颜色为红色。

所以我的问题是,我怎么才能找到td值startwith' - '?

$('td.numeric:startwith('-')").addClass("negative") 

CSS

.numeric { text-align:right; } 
.negative { text-align:right; color:red; } 
+0

这解决了你的问题:http://stackoverflow.com/questions/1824266/colorize-negative-positive-numbers-jquery – senthilbp

+0

有没有任何内置函数startwith没有正则表达式? –

+0

你不能在日期td上放一个类,只是使用'.not()'排除它们吗? – charlietfl

回答

1

您可以使用filter()

$("td.numeric").filter(function() { 
    return $.trim($(this).text()).indexOf("-") == 0; 
}).addClass("negative") 
+0

感谢它的工作。 –

0

试试这个:

$("td").each(function() { 
var text = $(this).text(); 
if (/[+-]?\d+(\.\d+)?/.test(text)) { 
var num = parseFloat(text); 
if (num < 0) { 
    $(this).addClass("negative"); //add negative class 
} else if (num > 0) { 
    $(this).addClass("positive"); //add positive class 
} 

} 
}); 
0

写这样说:

$('td.numeric').filter(function(){return this.innerHTML[0] === '-';}); 

或更安全的为:

$('td.numeric').filter(function(){return this.innerHTML.match(/^\s*-/;}); 

投入了大量的功能jQuery选择内就痛的性能,使用过滤器是更好的选择。