weixin_33709364 2014-01-13 17:10 采纳率: 0%
浏览 19

如何建立喜欢按钮?

I'm sorry if this question is very basic, unfortunately I'm everything but experienced with JS and frontend development in general. What I'm trying to accomplish is build a very simple like button (ala facebook) that changes after pressing it, so if I click like the button transitions to 'unlike', if I click unlike the button transitions to 'like'. I'm using Rails (4.0) and JQuery.

What I have right now is a button that works correctly on the backend, but doesn't work on the frontend i.e. it doesn't transition from like to unlike or from unlike to like correctly.

This is the partial that contains both buttons:

<div class="like-button">
  <% if current_user && current_user.liked?( object ) %>
    <%= link_to unlike_path( object ), method: :delete, remote: true, id: "like_button-#{ object.id }", class: 'like-button' do %>
      <span class="icon"></span>
      <span class="label m3">Non mi Piace</span>
    <% end %>
  <% else %>
    <%= link_to like_path( object ), method: :post, remote: true, id: "like_button-#{ object.id }", class: 'like-button' do %>
      <span class="icon"></span>
      <span class="label m3">Mi Piace</span>
    <% end %>
  <% end %>
</div>

Everything works correctly, I know it because it correctly checks the state of the button if I reload the page and it displays the right button. I'm not so sure about the JS unfortunately (also because I had very little visibility over frontend issues until now...):

$(".like-button").on("click", function () {
  $("#like_button_container").html("<%= render partial: 'shared/like', locals: { object: @likable } %>");
} );

What am I doing wrong? I've tried to change the class of the div containing the whole thing to id like_button_container but it still doesn't work.

Can someone shed a light?

TIA

  • 写回答

1条回答 默认 最新

  • weixin_33717298 2014-01-13 17:52
    关注

    You can achieve this using jQuery.

    Here is the html

    <input type="button" class="like"  value="like">
    
    <input type="button" class="unlike" style="display:none;" value="unlike">
    
    
    <script>
    $(function(){
    $(".like").click(function(){
    
      $(this).hide()
    $(".unlike").show()
    
    
    });
    $(".unlike").click(function(){
    
      $(this).hide()
    $(".like").show()
    //you can keep you logic here 
    //you can make server side increment of the likes/unlike using jquery ajax post or
    //any login you want to put
    
    })
    
    });
    
    </script>
    
    评论

报告相同问题?