我正在构建一个具有赞成和反对功能的Rails应用程序。 如果赞成票为> 0,我希望颜色更改为绿色,如果反对票为> 0,则颜色更改为红色。 我有一个像这样呈现页面的帮助程序,但我希望它在用户屏幕上更新而无需刷新页面。
索引.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,我希望背景改变颜色。
你只需要更改h1
标签中的class
,所以只需添加一个id
(就像你添加一个到它的子div
一样)并更新该元素在js.erb
文件中的class
。
索引.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
。
点赞.js.erb
$("#total-votes-<%= @post.id %>").html("<%= @post.vote_count %>")
$("#vote-<%= @post.id %>").attr("class", "<%= number_of_votes(@post.vote_count) %>");
因此,您将使用h1
标记的id
来更新其class
,就像您最初分配它的方式一样(即使用number_of_votes
助手)。