Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要使用jquery在条件上为td中的值着色吗_Jquery - Fatal编程技术网

要使用jquery在条件上为td中的值着色吗

要使用jquery在条件上为td中的值着色吗,jquery,Jquery,我想根据条件将负值涂成红色,我现在这样做: $('td.numeric:contains('-')").addClass("negative") 上面的代码查找类名为numeric的td,如果值包含“-”,则将类“negative”应用于该td 我的问题是,如果我将numeric类应用于例如日期值,该值也包含“-”作为分隔符,并使日期变为红色 所以我的问题是,我如何找到以“-”开头的td值 像 CSS 您可以使用: 试试这个: $("td").each(function() { var tex

我想根据条件将负值涂成红色,我现在这样做:

$('td.numeric:contains('-')").addClass("negative")
上面的代码查找类名为numeric的td,如果值包含“-”,则将类“negative”应用于该td

我的问题是,如果我将numeric类应用于例如日期值,该值也包含“-”作为分隔符,并使日期变为红色

所以我的问题是,我如何找到以“-”开头的td值

CSS

您可以使用:

试试这个:

$("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
 }

 }
 });
$(“td”)。每个(函数(){
var text=$(this.text();
如果(/[+-]?\d+(\.\d+)?/.test(文本)){
var num=parseFloat(文本);
if(num<0){
$(this.addClass(“负”);//添加负类
}如果(num>0),则为else{
$(this.addClass(“positive”);//添加positive类
}
}
});
这样写:

$('td.numeric').filter(function(){return this.innerHTML[0] === '-';});
或更安全,如:

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

在jquery selector中放置大量函数只会影响性能,使用过滤器是更好的选择。

这解决了您的问题:startwith是否有内置的函数没有regex?您不能将类放在日期td上,然后使用
.not()
简单地排除它们吗?
$("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
 }

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