有没有办法在两个不同 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/