javascript - 根据更新的记录更改背景颜色

标签 javascript ruby-on-rails

我正在构建一个具有赞成和反对功能的 Rails 应用程序。我希望如果赞成票 > 0,则颜色更改为绿色;如果反对票 > 0,则颜色更改为红色。我有一个助手可以像这样呈现页面,但我希望它在用户屏幕上更新而无需刷新页面。

index.html.erb

<div class="panel-left">
  <%= link_to 'Upvote', upvote_post_path(post), method: :patch, remote: true  %>
  <br />
  <%= link_to 'Downvote', downvote_post_path(post), method: :patch, remote: true %>

  <h1 class="<%=number_of_votes(post.vote_count) %>">
    <div id="total-votes-<%= post.id %>">
      <%= post.vote_count %>
    </div>
  </h1>
</div>

upvote.js.erb:

// this updates the counter: it works
$("#total-votes-<%= @post.id %>").html("<%= @post.vote_count %>")

//this is what I am not sure of, I hacked it together but it breaks everything (prevents the above from updating) and shows a server error in the console
if($('<%= escape_javascript @post.vote_count) %>') > 0) {
  $("<%=escape_javascript number_of_votes(post.vote_count) %>").attr('style', 'background-color: rgb(179, 144, 114)');
} else {
  $("<%= escape_javascript number_of_votes(post.vote_count) %>").attr('style', 'background-color: rgb(115, 227, 87)');
};

帖子助手

module PostsHelper
  def number_of_votes(votes)
    if votes > 0
      'positive-bg'
    elsif votes < 0
      'negative-bg'
    end
  end
end

正如我所说,一切正常,只是如果用户的投票足以将 @post.vote_count 更改为大于或小于 0,我希望背景更改颜色。

最佳答案

您只需更改 classh1标签,所以只需添加 id到它(以同样的方式向其子元素 div 添加一个)并更新该元素的 classjs.erb文件。

index.html.erb

<div class="panel-left">
  <%= link_to 'Upvote', upvote_post_path(post), method: :patch, remote: true %>
  <br />
  <%= link_to 'Downvote', downvote_post_path(post), method: :patch, remote: true %>

  <h1 id="vote-<%= post.id %>" class="<%=number_of_votes(post.vote_count) %>">
    <div id="total-votes-<%= post.id %>">
      <%= post.vote_count %>
    </div>
  </h1>
</div>

注意添加 id="vote-<%= post.id %>" ;那id将识别该元素并更改其 class .

upvote.js.erb

$("#total-votes-<%= @post.id %>").html("<%= @post.vote_count %>")
$("#vote-<%= @post.id %>").attr("class", "<%= number_of_votes(@post.vote_count) %>");

因此您将使用idh1标签更新其 class与您首先分配它的方式相同(即使用 number_of_votes helper)。

关于javascript - 根据更新的记录更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724526/

相关文章:

javascript - 指令中的 ng-click 不调用 Controller 范围中定义的函数

javascript - 字符串列表的输入效果。需要帮助确定事件顺序

javascript - 如何删除选择字段中的列表选项项?

ruby-on-rails - 安装 Rack 时出错

ruby-on-rails - 覆盖 rails #destroy 参数错误

javascript - 返回值给函数

javascript - 无法在 PHP 内回显以 ajax 发送的 POST 参数

ruby-on-rails - 为 ActiveAdmin Controller 设置过滤器 before_action

ruby-on-rails - 新兴 Rubyist 的最佳源代码

ruby-on-rails - 检查嵌套资源的当前父 Controller