繁体   English   中英

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

[英]How do I replace data toggle text with a glyphicon? (Using Rails and JS)

我正在使用acts_as_votable gem。 现在,“喜欢”和“不喜欢”按钮正常工作,并且将喜欢的对象保存到数据库中。 我需要将“喜欢”和“不喜欢”文本替换为Glyphicons。 现在它不起作用,因为数据:{toggle_text:'Like'部分仅接受文本值,并且JS连接了data-toggle-text。

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

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>

你可以尝试做这样的事情

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>

暂无
暂无

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

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