【问题标题】:How to change color font depending status?如何根据状态更改颜色字体?
【发布时间】:2018-01-23 16:58:40
【问题描述】:

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

如何实现?

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

【问题讨论】:

  • 你的表是如何创建的(如果你创建了它,你可以给td添加一个类)?你用 jquery 吗?
  • 我正在尝试使用以下代码:
  • @edwinbossman 您应该将该代码添加到您的问题中并解释错误是什么/为什么您认为它不起作用。
  • 我试过但格式不正确
  • @EdwinBossman 根据 MDN,fontcolor 方法已被弃用:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript jquery html css


【解决方案1】:

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

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

或者你可以使用原版 js:

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

这些类的css是这样的:

.approve {
color: green;
}

.pending{
color: yellow;
}

.rejected{
    color: red;
}

【讨论】:

  • 工作不正常,我在下面的答案中得到了答案,非常感谢
【解决方案2】:

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
  });
});
<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>

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2015-05-25
    • 2019-12-08
    • 2021-01-20
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多