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

Formatting number returned in js.erb file

本文关键字:格式化 编号 返回 erb 文件 js      更新时间:2023-09-26

我需要在我拥有的js.erb文件中格式化投票系统中返回的数字。当页面最初通过rails加载时,我可以为正数加上"+"号(也可以为负数加上"-"号),但在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 %>

好的,我知道你需要什么了。将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) %>");

看起来不漂亮,你可能需要稍微调整一下引号(改为/),但这符合你的要求。

编辑:

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

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