繁体   English   中英

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

[英]Formatting number returned in js.erb file

我需要格式化我拥有的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) %>");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM