Изменить <td>фон на основе процента в ячейке, а также добавить «%» к числу - PullRequest
1 голос
/ 01 марта 2012

Вот какая-то легкая репутация для кого-то.

Сценарий

У меня есть таблица, которая динамически создается с использованием JSP. Есть несколько <td> с числом в ячейке, представляющим процент. См. эту скрипку для примера. Мне нужно изменить цвет фона ячейки на основе процента, представленного в ячейке. Например:

value < 50 = Red
value >= 50 & < 90 = Yellow
value >= 90 = Green

Кроме того, мне нужно, чтобы содержимое ячейки добавлялось со знаком «%». Например:

90 = 90%

Вопрос

Как добавить цвет фона на основе содержимого ячейки и добавить к нему текст?

У меня есть несколько jQuery, которые я собирался использовать для этого, но он вообще не работает. Это тоже в скрипке . Я также хотел бы, чтобы это было как можно худее. Если это можно сделать в пару строк, это было бы здорово. Если бы это можно было сделать просто с помощью CSS, это было бы еще лучше , но я не думаю, что это возможно.

Код

(если вы не любите переходить по ссылкам)

CSS

.red {
    background-color: #f99;
}
.yellow {
    background-color: #ff9;
}
.green {
    background-color: #9f9;
}
.notApplicable {
    background-color: #fff;
}
td.stopGapCondition {
    text-align: center;
}​

JQuery

if ($('.stopGapCondition').text() < 50) {
    $('td .stopGapCondition').addClass('red');
}
if ($('.stopGapCondition').text() >= 50 && $('.stopGapCondition').text() < 90) {
    $('td .stopGapCondition').addClass('yellow');
}
if ($('.stopGapCondition').text() >= 90) {
    $('td .stopGapCondition').addClass('green');
}

HTML

<html>
  <head>
    <meta name="generator" content="HTML Tidy for Windows (vers 14 February 2006), see www.w3.org">
    <title></title>
  </head>
  <body>
    <table class="content bordered" border="3" cellspacing="2" cellpadding="3" valign="top">
      <tbody>
        <tr>
          <th class="stopGapTH" colspan="4">
            Patient List
          </th>
          <th class="stopGapTH" colspan="99">
            Clinical Adherence Information
          </th>
        </tr>
        <tr height="30">
          <th align="middle">
            Patient Name
          </th>
          <th align="middle">
            DOB
          </th>
          <th align="middle">
            Primary Disease
          </th>
          <th align="middle">
            Risk Index
          </th>
          <th>
            Athsma
          </th>
          <th>
            COPD
          </th>
          <th>
            Diabetes
          </th>
          <th>
            Heart Disease
          </th>
        </tr>
        <tr>
          <td>
            Louis Armstrong
          </td>
          <td>
            Blah
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition">
            50
          </td>
          <td class="stopGapCondition">
            80
          </td>
          <td class="stopGapCondition">
            75
          </td>
          <td class="stopGapCondition">
            90
          </td>
        </tr>
        <tr>
          <td>
            Bob Barker
          </td>
          <td>
            Blah
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition red">
            49
          </td>
          <td class="stopGapCondition yellow">
            50
          </td>
          <td class="stopGapCondition yellow">
            89
          </td>
          <td class="stopGapCondition green">
            90
          </td>
        </tr>
        <tr>
          <td>
            David Brinkley
          </td>
          <td>
            1Blah
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Tom Brokaw
          </td>
          <td>
            10Blah4
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Cad2 Sandy
          </td>
          <td>
            01Blah
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Cad3 Sandy
          </td>
          <td>
            0Blah
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Cad4 Sandy
          </td>
          <td>
            Blah5
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Cad5 Sandy
          </td>
          <td>
            01Blah5
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Alex Trebek
          </td>
          <td>
            1Blah1
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
        <tr>
          <td>
            Chucka Woolerya
          </td>
          <td>
            10Blah51
          </td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
          <td class="stopGapCondition"></td>
        </tr>
      </tbody>
    </table>
  </body>
</html>

РЕДАКТИРОВАТЬ: Кроме того, я забыл упомянуть, что если он не содержит числа, то есть он может содержать «na» или «n / a» или «не применимо», он должен быть белым , Я добавил CSS, но забыл упомянуть об этом в вопросе.

Ответы [ 5 ]

6 голосов
/ 01 марта 2012

Вам нужно использовать .each для итерации результатов;вы не можете применить одну операцию ко всем одновременно.

$('.stopGapCondition').each(function() {
    var $this = $(this);
    var value = $this.text();

    if(!/^\s*\d+(\.\d+)?\s*$/.test(value)) {
        $this.addClass('notApplicable');
        return;
    }

    if(value < 50) {
        $this.addClass('red');
    } else if(value < 90) {
        $this.addClass('yellow');
    } else {
        $this.addClass('green');
    }

    $this.text($this.text() + '%');
});​

Вот демонстрация.

2 голосов
/ 01 марта 2012
$('.stopGapCondition').each(function(){
    var $cell= $(this), val=parseInt( $cell.text())|| null, color='notApplicable';
    color=(val && val<50) ? 'red': (( val>=50 && val <=90)? 'yellow': (( val>90)? 'green': 'notApplicable'));    
    $cell.addClass(color); 
    if(val) $cell.text( val +' %');   
});

http://jsfiddle.net/R3AUh/18/

1 голос
/ 01 марта 2012

Это должно работать: http://jsfiddle.net/R3AUh/10/

0 голосов
/ 01 марта 2012

http://jsfiddle.net/R3AUh/19/

$('.stopGapCondition').each(function() {

    switch(true) {
        case ($(this).text() < 50 && $(this).text() !== ''):
            $(this).addClass('red');
            break;
        case ($(this).text() >= 50 && $(this).text() < 90):
            $(this).addClass('yellow');
            break;
        case ($(this).text() >= 90):
            $(this).addClass('green');
            break;
    }
});
0 голосов
/ 01 марта 2012

Поможет ли приведенный ниже код? Вы можете зациклить td с классом stopGapCondition

 $("table td.stopGapCondition").each(function(e){


    if ($(this).text() < 50) {

        $(this).addClass('red');
    }
    if ($(this).text() >= 50 && $(this).text() < 90) {

        $(this).addClass('yellow');
    }
    if ($(this).text() >= 90) {

        $(this).addClass('green');
    }

});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...