如何更改颜色字体依赖状态?

时间:2018-01-23 16:58:41

标签: javascript jquery html css

我想根据表中的状态动态更改颜色字体: 批准 - 绿色 待定 - 黄色 拒绝 - 红色

怎么能实现呢?

<div class="row">
    <table class="table" id="table">
        <tr>
            <th>Application</th>
            <th>Tier1</th>
            <th>Manager</th>
            <th>Director<br>
            <th>VP</th>
            <th>Overall</th>
        </tr>
        <tr>
            <td>OMS</td>
            <td>Approved</td>
            <td>Approved</td>
            <td>Pending</td>
            <td>Rejected</td>
            <td>Pending</td>
        </tr>
    </table>
</div>

2 个答案:

答案 0 :(得分:4)

您可以使用jquery添加相关的类:

$( "td" ).addClass( "approved" );
$( "td" ).addClass( "pending" );

或者您可以使用vanilla js:

  var element = document.getElementById("tdId");
    element.classList.add("approved");

这些类的CSS就像:

.approve {
color: green;
}

.pending{
color: yellow;
}

.rejected{
    color: red;
}

答案 1 :(得分:1)

&#13;
&#13;
var getColor = function(text) {
  if (text === "Approved") return 'green';
  if (text === "Pending") return 'yellow';
  if (text === "Rejected") return 'red';
  return "";
};

$('td').each(function(i, td) {
  var color = getColor($(td).html());
  $(td).css({
    "color": color
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <table class="table" id="table">
    <tr>
      <th>Application</th>
      <th>Tier1</th>
      <th>Manager</th>
      <th>Director<br>
        <th>VP</th>
        <th>Overall</th>
    </tr>
    <tr>
      <td>OMS</td>
      <td>Approved</td>
      <td>Approved</td>
      <td>Pending</td>
      <td>Rejected</td>
      <td>Pending</td>
    </tr>
  </table>
</div>
&#13;
&#13;
&#13;

希望有所帮助!