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

查看:38
本文介绍了Rails: make (link_to "example", "#", remote: true) 绕过 (respond_to ... format.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

在我的页面上,我有 2 个远程链接.第一个是:

On my page I have 2 remote links. The first is:

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

这是一个fadeToggle对象描述的简单链接:

which is a simple link to fadeToggle the description of an object:

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

第二个是 Ajax 调用:

The second one is an Ajax call:

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

and the controller is supposed to do STUFF when it gets clicked:

def objects

  ...

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

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

My problem is, that every time when I use the first link to toggle the description on or off, also STUFF happens which is not supposed to be the case. How can I avoid STUFF from happening when clicking on the first link?

推荐答案

第一个链接不需要remote: true.导致 jquery_ujs 尝试提交单击时通过ajax自动链接.删除 remote: true 应该可以防止切换链接触发 objects 操作.

The first link does not need remote: true. Setting that causes jquery_ujs to try to submit the link automatically via ajax when you click it. Removing remote: true should prevent the toggle link from triggering the objects action.

另外,您的 click 处理程序应返回 false 或调用 e.preventDefault() 以防止浏览器尝试跟随链接(基本上你是在告诉浏览器忽略这次点击,我处理了它"):

Separately, your click handler should either return false or call e.preventDefault() to prevent the browser from trying to follow the link (basically you're telling the browser "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

这篇关于Rails: make (link_to "example", "#", remote: true) 绕过 (respond_to ... format.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆