【问题标题】:jQuery - color tr by cell valuejQuery - 按单元格值着色 tr
【发布时间】:2023-03-22 11:00:01
【问题描述】:

长话短说 - 我正在显示股票交易表格并且试图将表格行颜色设置为红色或绿色,这意味着它是“买入”或“卖出”。

<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”到 greenBg,“S”到 redBg)并将颜色设置为整行,而不仅仅是第一个单元格?

提前致谢!

【问题讨论】:

    标签: javascript jquery html html-table


    【解决方案1】:

    这是一种方法:

    var classes = {
      'B': 'greenBg',
      'S': 'redBg'
    };
    
    $('table.dataframe tbody tr').addClass(function() {
       return classes[this.cells[2].textContent];
    });
    

    如果单元格的textContent 没有对应的键(textContent 不是BS),则函数返回undefined 并且addClass 不会向该行添加任何类。

    【讨论】:

      【解决方案2】:
      $(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
      
                 }
      
         });
      });
      

      【讨论】:

      • 非常感谢!这帮助很大!
      • @pmus 如果这有帮助..那么您可以接受答案
      【解决方案3】:

      您可以检查tdnth-childtr。所以它只检查你想要的值的表格单元格/行。

      我已经做了两个例子,一个是为整行着色,或者只是为选定的 td 着色

      // 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)

      【讨论】:

        猜你喜欢
        • 2013-08-01
        • 2013-01-09
        • 2011-08-19
        • 2016-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多