繁体   English   中英

Rails表 - 动态条件字体格式

[英]Rails Table - Dynamic Conditional Font Formatting

我试图设置动态值的字体颜色如下:if incident.state_id = 1 ,然后是红色字体,如果incident.state_id = 2 ,则为黄色字体,如果incident.state_id = 3 ,则为红色字体。

incident.state_id = 1 : state.name = "Pending Investigation"
incident.state_id = 2 : state.name = "Investigation in Progress"
incident.state_id = 3 : state.name = "Investigation Closed"

我已经采用了以下的coffeescript,但我知道zsch关于js / coffee,所以我不知道要改变什么来使这项工作。

目前,所有州的字段显示为红色。

incidents.js.coffee:

$(".state").each ->
  $this = $(this)
  value = $this.text()
  if value = 1
    $this.addClass "red"
  else if value = 2
    $this.addClass "yellow"
  else
    $this.addClass "green"

application.html.erb

td.state {
}

.red {
    color: #f99;
}
.yellow {
    color: #ff9;
}
.green {
    color: #9f9;
}

incidents.html.erb:

<td class="state"><%= incident.state.name %></td>

如果您的事件都是从服务器呈现的并且没有动态添加到页面中,那么您实际上并不需要任何JS来设置类。 只需创建一些使用状态ID的css类:

td {
  .state-1 {
    color: #f99;
  }
  .state-2 {
    color: #ff9;
  }
  .state-3 {
    color: #9f9;
  }
}

您的视图将如下所示:

<td class="<%= state-#{incident.state_id} %>"><%= incident.state.name %></td>

为什么要烦扰咖啡脚本(为此)?

相反,我建议在erb文件中设置正确的类,如下所示:

<% if incident.state_id == 1  %>
    <td class="red"><%= incident.state.name %></td>
<% elsif incident.state_id == 2 %>
    <td class="yellow"><%= incident.state.name %></td>
<% else %>
    <td class="green"><%= incident.state.name %></td>
<% end %>

这可能不是最干净的方法,但应解决眼前的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM