我正在构建一个具有赞成和反对功能的 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,我希望背景更改颜色。
最佳答案
您只需更改 class
在h1
标签,所以只需添加 id
到它(以同样的方式向其子元素 div
添加一个)并更新该元素的 class
在 js.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) %>");
因此您将使用id
的h1
标签更新其 class
与您首先分配它的方式相同(即使用 number_of_votes
helper)。
关于javascript - 根据更新的记录更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724526/