Javascript Rails表-动态条件字体格式
我试图将动态值的字体颜色设置如下:如果Javascript Rails表-动态条件字体格式,javascript,css,ruby-on-rails,coffeescript,Javascript,Css,Ruby On Rails,Coffeescript,我试图将动态值的字体颜色设置如下:如果incident.state\u id=1,则设置红色字体;如果incident.state\u id=2,则设置黄色字体;如果incident.state\u id=3,则设置红色字体 incident.state_id = 1 : state.name = "Pending Investigation" incident.state_id = 2 : state.name = "Investigation in Progress" incident.st
incident.state\u id=1
,则设置红色字体;如果incident.state\u id=2
,则设置黄色字体;如果incident.state\u 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,但是我对js/coffee非常了解,所以我不知道要改变什么才能使它工作
当前,所有状态字段显示为红色
事件。js.咖啡:
$(".state").each ->
$this = $(this)
value = $this.text()
if value = 1
$this.addClass "red"
else if value = 2
$this.addClass "yellow"
else
$this.addClass "green"
<td class="state"><%= incident.state.name %></td>
application.html.erb
td.state {
}
.red {
color: #f99;
}
.yellow {
color: #ff9;
}
.green {
color: #9f9;
}
incents.html.erb:
$(".state").each ->
$this = $(this)
value = $this.text()
if value = 1
$this.addClass "red"
else if value = 2
$this.addClass "yellow"
else
$this.addClass "green"
<td class="state"><%= 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 %>
这可能不是最干净的方法,但应该可以解决眼前的问题。如果事件都是从服务器呈现的,并且没有动态添加到页面中,那么您实际上不需要任何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>
所有事件是否在服务器上一次性呈现?用户可以从页面更改事件状态吗?如果value=1
不做您认为它做的事情,如果value==1
OTOH…严重吗?那容易吗?!谢谢-我想得太多了。这不能解决事件在加载后动态添加到页面的情况。而且,if开关不像下面的css类那么干。@steakchaser我同意。我更喜欢你的答案。我离开rails的时间太长了,所以我给出了我确信有效的答案,而不是你的ERB,我不记得了。谢谢steakchaser。这些值是动态拉取的,但感谢您的响应!