2017-02-26 26 views
0

我正在使用acts_as_votable gem。現在喜歡和不喜歡的按鈕功能正常,喜歡的東西被保存到數據庫。我需要的是將「喜歡」和「不喜歡」的文字替換爲字形。它現在不起作用,因爲數據:{toggle_text:'Like'部分只接受文本值,並且JS連接到數據切換文本。如何使用圖形替換數據切換文本? (使用Rails和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

你可以嘗試做這樣的事情

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> 
+0

感謝。但是,它看起來並不奏效,它以純文本顯示,而不是將其呈現爲圖形。 – Joshua

+0

@Joshua你能檢查一個改進的答案嗎? – bgs

+0

工作完美!乾杯。 – Joshua