js.erb文件中返回的格式编号

时间:2015-12-16 02:59:58

标签: javascript ruby-on-rails erb

我需要格式化我在js.erb文件中的投票系统中返回的数字。我可以预先添加" +"当页面最初通过rails加载时(和#34; - "对于负数的符号)签署正数,但在javascript上我不确定如何添加相同的数字。这是我的_like.js.erb:

$('.like')
    .on('ajax:send', function () { $(this).addClass('loading'); })
    .on('ajax:complete', function () { $(this).removeClass('loading'); })
    .on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); })
    .on('ajax:success', function (e, data, status, xhr) { $("#comment_<%= comment.id %>").html('<%=escape_javascript comment.cached_votes_score.to_s %>').hide().fadeIn(500); });

$('.unlike')
    .on('ajax:send', function () { $(this).addClass('loading'); })
    .on('ajax:complete', function () { $(this).removeClass('loading'); })
    .on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); })
    .on('ajax:success', function (e, data, status, xhr) { $("#comment_<%= comment.id %>").html('<%=escape_javascript comment.cached_votes_score.to_s %>').hide().fadeIn(500); });

这是我的html.erb部分:

<%= link_to unlike_post_post_comment_path(post, comment), class: "unlike", method: :put, remote: true do %>
    <button type="button" class="btn btn-xs btn-danger" aria-label="Left Align">
        <span><i class="fa fa-thumbs-o-down"></i></span>
    </button>
<% end %>
<%= link_to like_post_post_comment_path(post, comment), class: "like", method: :put, remote: true do %>
    <button type="button" class="btn btn-xs btn-info" aria-label="Left Align">
        <span><i class="fa fa-thumbs-o-up"></i></span>
    </button>
<% end %>
<% if comment.cached_votes_score > 0 %>
    <span class="badge like vote-score" id="comment_<%= comment.id %>"><%= "+ #{comment.cached_votes_score}" %></span>
<% elsif comment.cached_votes_score < 0 %>
    <span class="badge like vote-score" id="comment_<%= comment.id %>"><%= "- #{comment.cached_votes_score.abs}" %></span>
<% else %>
    <span class="badge like vote-score" id="comment_<%= comment.id %>"><%= comment.cached_votes_score %></span>
<% end %>

1 个答案:

答案 0 :(得分:1)

好的,我知道你需要什么。将ajax:success回调中的代码更改为以下内容:

$("#comment_<%= comment.id %>").html("<%= comment.cached_votes_score > 0 ? "+ #{comment.cached_votes_score.to_s}" : (comment.cached_votes_score < 0 ? "- #{comment.cached_votes_score.to_S}" : comment.cached_votes_score.to_s) %>");

看起来不漂亮,你可能不得不稍微使用引号(改变&#34;到/&#34;),但这适用于你想要的。

编辑:

另一种方法是使用sprintf。不确定你是否特别想在+和数字之间留一个空格,但试试这个:

$("#comment_<%= comment.id %>").html("<%= sprintf("%+d", comment.cached_votes_score) %>");