Rails: make (link_to "example", "#", remote: true) 绕过 (respond_to ... format.js)

Rails: make (link_to "example", "#", remote: true) bypass (respond_to ... format.js)

我有以下问题:

在我的页面上,我有 2 个远程 link。第一个是:

<p><%= link_to "Description", "#", remote: true, id: "desc-link" %></p>

这是一个简单的link淡入淡出切换对象的描述:

$(document).on "ready page:load", ->
  $("section.object").on "click", "#desc-link",  ->
    $("#object-desc").fadeToggle()

第二个是 Ajax 调用:

<a type="button" class="btn btn-default", 
  href='/users/<%= Object.find(object_to_display).user.id %>/objects',
  data-remote="true" id='object-link'>Test</a>

并且控制器应该在被点击时执行 STUFF:

def objects

  ...

  respond_to do |format|
    format.html { render "users/show_objects" }
    format.js { STUFF }
  end
end

我的问题是,每次当我使用第一个 link 打开或关闭描述时,也会发生 STUFF,这本不应该是这种情况。单击第一个 link 时如何避免 STUFF 发生?

第一个link不需要remote: true。导致 jquery_ujs 在您单击时尝试通过 ajax 自动提交 link 的设置。删除 remote: true 应该可以防止切换 link 触发 objects 操作。

另外,您的 click 处理程序应该 return false 或调用 e.preventDefault() 以防止浏览器尝试遵循 link(基本上您'告诉浏览器 "ignore this click, I handled it"):

$(document).on "ready page:load", ->
  $("section.object").on "click", "#desc-link", (e) ->
    $("#object-desc").fadeToggle()
    e.preventDefault() // <-- prevents following the link