RoR 和 json:更新按钮点击次数

大卫

我正在尝试通过单击我的页面上的按钮来更新我的视图,而无需刷新页面

应用程序.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

有什么建议么?

大卫

答案是我只是在点击后用 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>

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章