如果值大于0,如何更改表格数据颜色

时间:2019-06-10 12:24:12

标签: javascript html css

我正在编码一个交易表,该交易表应以红色显示借方值,以绿色显示贷方值,但是我希望这种颜色仅在使用javascript的表数据大于0时才生效。请帮助...

df = pd.DataFrame( { 'category': ['Cosmetics', 'Fruits', 'Clothes'],
                     'value': [789.99,27.68, 179.20],
                    'percentage_difference': [300.0,400.0,500.0]})
df['merge_value'] = df.apply(lambda r: "{0}({1}, {2}%)".format(r['category'], r['value'], r['percentage_difference']), axis=1)

1 个答案:

答案 0 :(得分:0)

通过查看html,看来您正在使用数据表,因此您必须使用jQuery,这就是我的处理方法。

$(document).ready(function() {
  var table = $('#example').DataTable({
    columnDefs: [{
      targets: 3,
      render: function(data, type, row) {
        var color = 'black';
        if (data < 0) {
          color = 'red';
        }
        if (data > 0) {
          color = 'green';
        }
        return '<span style="color:' + color + '">' + data + '</span>';
      }
    }]
  });
});
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>


<!DOCTYPE html>
<div class="container">
  <table id="example" class="display nowrap" width="100%">
    <thead>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </thead>

    <tfoot>
      <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Age</th>
        <th>Start date</th>
        <th>Salary</th>
      </tr>
    </tfoot>

    <tbody>
      <tr>
        <td>Tiger Nixon</td>
        <td>System Architect</td>
        <td>Edinburgh</td>
        <td>61</td>
        <td>2011/04/25</td>
        <td>$3,120</td>
      </tr>
      <tr>
        <td>Garrett Winters</td>
        <td>Director</td>
        <td>Edinburgh</td>
        <td>-3</td>
        <td>2011/07/25</td>
        <td>$5,300</td>
      </tr>
      <tr>
        <td>Ashton Cox</td>
        <td>Technical Author</td>
        <td>San Francisco</td>
        <td>66</td>
        <td>2009/01/12</td>
        <td>$4,800</td>
      </tr>
      <tr>
        <td>Cedric Kelly</td>
        <td>Javascript Developer</td>
        <td>Edinburgh</td>
        <td>22</td>
        <td>2012/03/29</td>
        <td>$3,600</td>
      </tr>
      <tr>
        <td>Jenna Elliott</td>
        <td>Financial Controller</td>
        <td>Edinburgh</td>
        <td>33</td>
        <td>2008/11/28</td>
        <td>$5,300</td>
      </tr>
      <tr>
        <td>Brielle Williamson</td>
        <td>Integration Specialist</td>
        <td>New York</td>
        <td>-61</td>
        <td>2012/12/02</td>
        <td>$4,525</td>
      </tr>
    </tbody>
  </table>
</div>