2015-09-23 2 views
0

Короче говоря, я показываю таблицу торгуемых акций и, пытаясь установить цвета строк таблицы красного или зеленого цвета, что означает «купить» или «продать».jQuery - цвет tr по значению ячейки

<table border="1" class="dataframe"> 
    <thead> 
    <tr style="text-align: right;"> 
     <th></th> 
     <th>board</th> 
     <th>buysell</th> 
     <th>openinterest</th> 
     <th>price</th> 
     <th>quantity</th> 
     <th>seccode</th> 
     <th>secid</th> 
     <th>time</th> 
     <th>tradeno</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <th>1</th> 
     <td>FUT</td> 
     <td>B</td> 
     <td>2912686</td> 
     <td>67686</td> 
     <td>100</td> 
     <td>SiZ5</td> 
     <td>3630</td> 
     <td>23.09.2015 11:12:27</td> 
     <td>1239572664</td> 
    </tr> 

...etc

с помощью JQuery:

$("tr:contains('B')").addClass('greenBg'); 
$("tr:contains('S')").addClass('redBg'); 

, но это на самом деле цвета строки на основе всего содержимого.

Итак, как я могу обратиться к нему, чтобы проверить значение ячейки «buysell» («B» на «зеленый», «S» на redBg) и установить цвет для всей строки, а не только для первой ячейки?

Заранее благодарен!

ответ

4

Это один из способов сделать это:

var classes = { 
    'B': 'greenBg', 
    'S': 'redBg' 
}; 

$('table.dataframe tbody tr').addClass(function() { 
    return classes[this.cells[2].textContent]; 
}); 

Если нет соответствующего ключа для ячейки textContent (textContent не B или S), функция возвращает undefined и addClass не добавьте любой класс в эту строку.

0
$(document).ready(function(){ 
    $('table.dataframe tr td').each(function(){ 
      if($(this).text() == 'B'){ 
       $(this).addClass('greenBg'); //colors the td 
      //$(this).parent().addClass('greenBg'); //colors the entire row 

      } 
    else if($(this).text() == 'S'){ 
       $(this).addClass('redBg'); 
      //$(this).parent().addClass('redBg'); //colors the entire row 

      } 

    }); 
}); 
+0

Спасибо Вея много! Это очень помогло! – pmus

+0

@pmus, если это помогло ... тогда вы можете принять ответ – coolguy

0

Вы можете проверить td или trnth-child. Так что это только проверка ячейки/строки таблицы нужного значения.

Я сделал два примера один из окрашивая всю строку или только окраски выбранного td «s

// Checks through the td elements which contain 'B' or 'S' 
$("td:nth-child(3):contains('B')").addClass('greenBg'); 
$("td:nth-child(3):contains('S')").addClass('redBg'); 

JSFIDDLE EXAMPLE (Color to only the TD)

// Checks through tr elements and find the td elements which contain 'B' or 'S' 
$("tr:has(td:nth-child(3):contains('B'))").addClass('greenBg'); 
$("tr:has(td:nth-child(3):contains('S'))").addClass('redBg'); 

JS FIDDLE EXAMPLE (Color to the whole row)