如何使用glyphicon替换数据切换文本? (使用Rails和JS)

时间:2017-02-26 13:56:31

标签: javascript jquery ruby-on-rails ruby

我正在使用acts_as_votable gem。现在喜欢和不喜欢按钮正常运行,喜欢的东西保存到数据库。我需要的是替换" Like"和"不喜欢"文字变成Glyphicons。它现在不起作用,因为数据:{toggle_text:' Like' 部分只接受文本值,并且JS连接到数据切换文本。

我该如何处理?谢谢你的帮助。

likes.js.coffee文件

$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
  # update counter
  $(".votes-count[data-id=#{data.id}]").text data.count

  # toggle links
  $("a.vote[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.text()
    $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    return

  return

show.html.erb文件

<% if current_user.liked? @review %>
<%= link_to "Dislike", dislike_review_path(@review), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_review_path(@review), id: @review.id } %>
<% else %>
<%= link_to "Like", like_review_path(@review), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_review_path(@review), id: @review.id } %>
<% end %>

<span class="votes-count" data-id="<%= @review.id %>">
<%= @review.get_likes.size %>
</span>
users like this
<br>

1 个答案:

答案 0 :(得分:1)

您可以尝试做类似的事情

<强> likes.js.coffee

$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
  # update counter
  $(".votes-count[data-id=#{data.id}]").text data.count

  # toggle links
  $("a.vote[data-id=#{data.id}]").each ->
    $a = $(this)
    href = $a.attr 'href'
    text = $a.html()
    $a.html($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
    $a.data('toggle-text', text).data 'toggle-href', href
    return

  return

<强> show.html.erb

<% if current_user.liked? @review %>
  <%= link_to '<i class="glyphicon glyphicon-star"></i>'.html_safe, dislike_review_path(@review), class: 'vote', method: :put, remote: true, data: { toggle_text: "<i class='glyphicon glyphicon-star-empty'></i>".html_safe, toggle_href: like_review_path(@review), id: @review.id } %>
<% else %>
  <%= link_to '<i class="glyphicon glyphicon-star-empty"></i>'.html_safe, like_review_path(@review), class: 'vote', method: :put, remote: true, data: { toggle_text: "<i class='glyphicon glyphicon-star'></i>".html_safe, toggle_href: dislike_review_path(@review), id: @review.id } %>
<% end %>

<span class="votes-count" data-id="<%= @review.id %>">
<%= @review.get_likes.size %>
</span>
users like this
<br>