【问题标题】:RoR and json: Update a count on button clickRoR 和 json:更新按钮点击次数
【发布时间】:2020-08-02 10:13:30
【问题描述】:

我正在尝试在不刷新页面的情况下单击我的页面上的按钮来更新我的视图

应用程序.js

$(document).on('ajax:success', '.follow-btn-show', function(e){
  let data = e.detail[0];
  let $el = $(this);
  let method = this.dataset.method;
  if (method === 'post') {
    $el.text('Unfollow');
    this.dataset.method = 'delete';
  } else if (method === 'delete') {
    $el.text('Follow');
    this.dataset.method = 'post';
  }
});

这非常适合按钮更改,但是如何让我的计数在点击到不同的 div 时更新?我试着附上这个:

$(this).text(${data.count});

但它会在我不想要的按钮上更新,并且我没有将 div 属性分配给那里的脚本。我需要分配属性并更新它,但我不知道如何。

我在视图中的计数

<div class="loop"><b><%= @user.followers.count %></b></div> Followers

控制器

def create
    current_user.follow(@user)
    respond_to do |format|
      format.html
      format.json do
        render json: { count: @user.followers.count },
               status: :created  
      end
    end
  end

  def destroy
    current_user.unfollow(@user)
    respond_to do |format|
      format.html
      format.json do
        render json: { count: @user.followers.count }, 
               status: :ok
      end
    end
  end

有什么建议吗?

ty

【问题讨论】:

  • DOM traversalmanipulating elements 上的一些基本jquery 教程开始。这不是一个代码编写服务,您需要做最少的努力来研究和解决问题。
  • 对不起,我只是不知道把代码放在哪里而不是代码本身,因为我需要和你提供的js集成。也许对你来说很容易,对新手来说并不容易。我正在尝试,我只是还没有做好。感谢您的链接。
  • 这并不难,但您并没有真正指定按钮与显示计数的位置之间的连接(如果有的话)。您需要首先弄清楚如何将两者连接起来,然后各个部分就会到位。你知道教一个人钓鱼等等。如果你不断得到你不知道如何修改的勺子代码,我真的是在伤害你。
  • 我理解您提供的代码并从中获取了很多(非常感谢)。问题是我不知道在脚本中的哪个位置附加我自己的代码。我曾尝试在这里和那里附加代码,但它要么呈现在按钮上,要么没有任何效果。这非常令人沮丧。公平地说,您知道我在上一个问题中询问了计数。这不是新的。我不是想利用,我真的被卡住了。我最终会自己得到它,但轻推会有所帮助。

标签: javascript ruby-on-rails json


【解决方案1】:

答案是我只是在点击后重新加载带有 id 的 div...

$(document).on('ajax:success', '.follow-btn', function(e) {
  let data = e.detail[0];
  let method = this.dataset.method === 'post' ? 'delete' : 'post';
  let txt = {
    post: 'Follow',
    delete: 'Unfollow'
  }[method];
  //loop
  $(`.follow-btn[href="${this.getAttribute('href')}"]`).each(function() {
    this.dataset.method = method;
    $(this).text(`${txt}`);
  });
   $("#following_count").load(" #following_count > *")
});

在我看来

<div id="following_count" class="inline">...<%= current_user.following.count %>...</div>

不确定这是多么有效或故障安全,但它确实有效。

【讨论】:

    猜你喜欢
    • 2020-11-22
    • 2014-01-18
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多