当点击它时,rails 改变我喜欢按钮的背景:

问题描述

我正处于我的 rails 应用程序 (instagram-clone) 的最后一步,问题是当我点击心形标志时,喜欢的数量从 0 升级到 1 但是,我找不到解决方案当我点击它时将我的徽标的背景颜色更改为“红色”,this is my logo image

这是我的Vote.js.erb:


<% if current_user.liked? @post %>
    $(".like-button").addClass("liked");
<% else %>
    $(".like-button").removeClass("like-button");
<% end %>
$(".likes-count").html(" <%= @post.get_upVotes.size%> ")

#i want to modify this lines to change the background color of my heart logo to red when the count of likes was upgraded from 0 to 1 and thanks a lot

这是我喜欢的按钮代码行:

<%= link_to like_post_path(post),class:"like-button",method: :put,remote: :true do %>
    <div>
      <i class="fas fa-heart fa-2x"></i>
    </div>
    <% end %>
<span class="likes-count"><%= post.get_upVotes.size %></span>

enter image description here

解决方法

好的,这是您的选择。 您可能正在查看和滚动列表中的许多故事/照片。

这是适合这种情况的修复程序。

vote.js.erb 中的一些变化:

<% if current_user.liked? @post %>
    $(".like-button-<%= @post.id %> .fas").addClass("liked");
<% else %>
    $(".like-button-<%= @post.id %> .fas").removeClass("liked");
<% end %>

$(".likes-count").html(" <%= @post.get_upvotes.size%> ")

当您使用图标时,在样式中的某处添加类似于下面的 css。

  .liked {
    color: red;
  }

以及你的 html 按钮的一些变化

<%= link_to like_post_path(post),class: "like-button-#{post.id}",method: :put,remote: :true do %>
    <div>
      <i class="fas fa-heart fa-2x <%= 'liked' if current_user.liked?(post) %>"></i>
    </div>
<% end %>