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>
    
    评论

报告相同问题?

悬赏问题

  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 pycharm运行main文件,显示没有conda环境
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?
  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上