javascript - 将局部变量传递到另一个 View 的 JS - Rails

标签 javascript jquery ruby-on-rails

有没有办法在两个不同 View 之间获取/获取 js 内的变量?假设我有一个带有以下内容的索引 View :

<% foo.each do |foo| %>
  <%= link_to 'bar', bar_path %> 
<% end %>

然后在 bar 中,我想使用 foo.id 选择器将一些 jQuery 添加到特定元素:

$('div#<%= foo.id %>').fadeOut(); // I know the interpolation wouldn't work here

我知道我可以使用我的路径将 foo.id 传递给 bar 或通过 locals 哈希发送它,但我该如何“用 jQuery 抓取”它?

最佳答案

您可以使用名为gon的gem轻松地将变量传递给JS。 .

gem "gon"

您所要做的就是将此 gem 添加到 Gemfile 中,然后您可以在任何 Controller 中调用 gon,如下所示:

class PaymentsController < ApplicationController

  def new
    ...
    gon.controller = "payments"
    gon.action    = "new"
    gon.message   = "Hello World!"
    ...
  end 
end

现在,在任何 javascript(在以下情况下为 CoffeeScript )中,您可以:

$ ->

  # Check if it is the target controller and action
  if gon? && gon.controller is "payments" &&  gon.action is "new"
    alert gon.message 

关于javascript - 将局部变量传递到另一个 View 的 JS - Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32686608/

相关文章:

mysql - MySQL 复合索引中键的高性能排序(WRT Rails 多态关联和 STI)

ruby-on-rails - rails : validate fields on association

ruby-on-rails - 索引显示顺序

javascript - 根据自身大小和当前偏移量动态更改元素偏移量

javascript - 为什么我通过 BLE 向设备发送数据时看不到任何通知?

javascript - 我如何才能只删除文本中的最后一个数字

javascript - Ajax、PHP 和 MySQL 以及在页面中附加数据

javascript - 我可以使用 .js 文件进行 TSLint 配置吗?

jquery - 当选项数不大于 1 时,自动选择选择中的第二个选项

jquery every 防止警报循环