简体   繁体   English

如何建立喜欢按钮?

[英]How do I build a like button?

I'm sorry if this question is very basic, unfortunately I'm everything but experienced with JS and frontend development in general. 很抱歉,如果这个问题很基本,很遗憾,除了JS和前端开发方面的经验之外,我什么都没有。 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'. 我要完成的工作是构建一个非常简单的like按钮(ala facebook),按下该按钮后会发生变化,因此,如果我单击按钮就像按钮转变为“不喜欢”一样,如果我单击不喜欢,按钮就会转变为“喜欢”。 I'm using Rails (4.0) and JQuery. 我正在使用Rails(4.0)和JQuery。

What I have right now is a button that works correctly on the backend, but doesn't work on the frontend ie 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...): 不幸的是,我对JS不太确定(也是因为到目前为止,我对前端问题的了解很少...):

$(".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. 我试图将包含整个内容的div的类更改为id like_button_container,但它仍然无法正常工作。

Can someone shed a light? 有人可以照亮吗?

TIA TIA

You can achieve this using jQuery. 您可以使用jQuery来实现。

Here is the html 这是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>

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

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