javascript - 如何根据条件栏向表行添加类?

标签 javascript ruby-on-rails ruby

我有一个包含条目的表。每个条目都有日期时间、文本、卡路里。如果当天的总卡路里低于预期值,我需要将所有行设为绿色,否则将其设为红色。在我的索引操作中,我有@total(这是要比较的值),最后我有两个数组,其中包含好的(绿色)日期和坏的日期。

def index
@entries = Entry.all
@total = 50
@total2 = Entry.all
@a = {}
Entry.all.each do |entry|
  if @a.key?(entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10])
    @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += (entry.calory)
  else  
    @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] = 0
    @a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += entry.calory
  end
end
@good = []
@bad = []
@a.each do |c|
  if c[1] < @total
    @good.append(c[0])
  else
    @bad.append(c[0])
  end
end

结束

然后在我的index.html.erb 中,我循环遍历行并尝试更改其颜色(如果该值位于好数组或坏数组中)。但它把一切都染成了绿色。

  <script type="text/javascript">
  var a = '<%=@a%>';
  var final = '<%=@final%>';
  var good = '<%=@good%>';
  var bad = '<%=@bad%>';
  console.log(good);
  $('#entries tr').each(function() {
    var date = $(this).find("td:first-child").text();
    if (good.substring(date) !== -1) {
      $(this).find("td:first-child").addClass('good');
    } else {
      $(this).find("td:first-child").addClass('bad');
    }
});

</script>

这是我的 table

Time    Text    Calory  Show    Edit    Destroy 
2016-12-24 10:00:00 first   23  Show    Edit    Destroy
2016-12-24 11:58:00 second  45  Show    Edit    Destroy
2016-12-24 12:59:00 third   56  Show    Edit    Destroy
2016-12-28 12:29:00 sds 34  Show    Edit    Destroy
2016-12-24 10:00:00 dewq    34  Show    Edit    Destroy

这里是console.log(好):[“2016-12-28”] 这是console.log(坏):[“2016-12-24”]

这是每个日期的 console.log(date):

2016-12-24 10:00:00
2016-12-24 11:58:00
2016-12-24 12:59:00
2016-12-28 12:29:00
2016-12-24 10:00:00

最佳答案

你只需要使用indexOf;根据您的示例数据,这应该有效:

$('#entries tr').each(function() {
   var date = $(this).find("td:first-child").text();
   if(date.indexOf(bad[0].toString()) > -1){
     $(this).find("td:first-child").addClass('bad');
   }
   if(date.indexOf(good[0].toString()) > -1){
     $(this).find("td:first-child").addClass('good');
   }
});

工作 fiddle :https://jsfiddle.net/e0sn1d0k/3/

关于javascript - 如何根据条件栏向表行添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41382491/

相关文章:

php - 如何在 ruby​​ 文件中执行 php 脚本

javascript - 如何将 Ruby 哈希输出为 Javascript?

ruby-on-rails - 在 Windows 上安装 rmagick gem

ruby-on-rails - 如何安全地解析来自 Ruby 哈希的数据?

javascript - timeago.js timeago 函数内联

javascript - 为什么从外部 Angular 调用的服务不是单例?

javascript - 进行页面刷新时防止显示未设置样式的页面

javascript - JavaScript 匿名函数的参数

ruby-on-rails - PostgreSQL 复杂索引类型和排序

ruby-on-rails - 为什么我在 bundle exec 中执行环境后 rake 中止