简体   繁体   English

在Jquery中选择nth-child和条件格式不起作用

[英]Selecting nth-child in Jquery and conditional formatting not working

I have a table and i want to format certain data fields based on their content. 我有一张桌子,我想根据它们的内容来格式化某些数据字段。 So for example if a field is less than 95% it should be red. 因此,例如,如果字段小于95%,则应为红色。

This is the jquery i'm using 这是我正在使用的jQuery

$(function(){
    $('#ConditionalTable td:nth-child(2n - 4)').each(function(){
        var Sales = $(this).text();
        if (Sales > '95%')  {
            $(this).css('backgroundColor', '#f76e6e'); 
        } else {
            $(this).css('backgroundColor', '#99faa0'); 
        }
    });
});

It currently selects every second column and turns it green. 当前,它每隔一列选择一次并将其变为绿色。

However i want it to skip the first 3 columns (these contain titles) and only start applying the formatting from the 4th column. 但是我希望它跳过前3列(这些包含标题),而仅从第4列开始应用格式。

So the 4th column would have formatting applied then the 6th, 8th etc. 因此,第4列将应用格式,然后是第6、8等。

Also for some reason no matter what value is in my table it's being turned green. 同样由于某种原因,无论我表中的值是多少,它都变成了绿色。 So in my code i've said if Sales are greater than 95% it should be green, otherwise red. 因此,在我的代码中,我曾说过如果Sales大于95%,则应该为绿色,否则为红色。 But this doesn't seem to be happening. 但这似乎没有发生。

Change #ConditionalTable td:nth-child(2n-4) to #ConditionalTable td:nth-child(2n+4) #ConditionalTable td:nth-child(2n-4)更改为#ConditionalTable td:nth-child(2n+4)

$(function(){
    $('#ConditionalTable td:nth-child(2n + 4)').each(function(){
        var Sales = parseInt($(this).text().replace('%',''),10);
        if (Sales > 95)  {
            $(this).css('backgroundColor', '#f76e6e'); 
        } else {
            $(this).css('backgroundColor', '#99faa0'); 
        }
    });
});

The value of n will be 0,1,2,3,..... in this case it will select 4,6,8,10,..... children n的值将是0,1,2,3,.....在这种情况下,它将选择4,6,8,10,.....子级

You can't compare the % values as in the code , so you need to convert it into integer or float and then compare 您无法像代码中那样比较%值,因此需要将其转换为整数或浮点数,然后进行比较

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM