【问题标题】:rails change the background of my like button when clicks on it :当点击它时,rails会改变我的like按钮的背景:
【发布时间】:2021-08-20 18:00:49
【问题描述】:

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

这是我的投票.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>

【问题讨论】:

  • ruby 模板是在服务器端渲染的,对吧?
  • 那个标志在哪里?请显示minimal reproducible example
  • edit添加更多信息的问题,请参阅minimal reproducible example - 特别是我们想看看您的“标志”是如何呈现的 - 例如它只是没有透明背景的图像吗?
  • 尝试:$(".like-button i.fa-heart").css("background-color", "red")$(".like-button").addClass("liked"); 行之后

标签: javascript jquery ruby erb ruby-on-rails-6


【解决方案1】:

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

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

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 %>

【讨论】:

  • 非常感谢@Hiren 完全理解这个概念,但是当我尝试这样做时,我得到了这个错误:未定义的方法id' for nil:NilClass in this line `
  • 糟糕,抱歉更新了该行作为答案。只需在post 之前删除@
  • 感谢兄弟您的时间,喜欢的计数仍然有效,但背景颜色没有改变。我想我的班级名称或类似的东西有问题......
  • 请检查给定的css类是否应用于标签/元素?
  • 是的@hiren :)
猜你喜欢
  • 2015-02-10
  • 2015-01-03
  • 2020-10-11
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2013-12-09
相关资源
最近更新 更多