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