javascript 将实例变量传递给 js.erb 文件(Rails 3 / jQuery)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6003501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing instance variable to js.erb file (Rails 3 / jQuery)
提问by neon
I have an "index.html.erb" file with the following:
我有一个“index.html.erb”文件,内容如下:
<%= render @users %>
<%= 渲染@users %>
This renders "_user.html.erb" and outputs a button for performing a certain action on each user:
这将呈现“_user.html.erb”并输出一个按钮,用于对每个用户执行特定操作:
<%= link_to "action", action_path(user), :id => "#{user.id}_action", :remote => true) %>
<%= link_to "action", action_path(user), :id => "#{user.id}_action", :remote => true) %>
I've set up my User controller to respond to the AJAX request by looking at "action.js.erb".
我已经通过查看“action.js.erb”设置了我的用户控制器来响应 AJAX 请求。
In order to perform javascript methods on particular users within the partial, and I'd like to know how instance variables from my partial (such as user.id) can be passed into or accessed within the js.erb file, for instance:
为了对局部中的特定用户执行 javascript 方法,我想知道如何将局部中的实例变量(例如 user.id)传入或访问 js.erb 文件,例如:
$("#{@user.id}_action").toggle();
回答by Magnar
You access the information in your *.js.erb
-files just like in your *.html.erb
-files, using @users
or other instance variables declared in the controller:
您可以*.js.erb
像访问-files 一样访问-files 中的信息*.html.erb
,使用@users
控制器中声明的using或其他实例变量:
$("#<%= @user.id %>_action").toggle();
回答by Nuriel
there's an excellent gem called gon that might simplify and organize things quite a bit: https://github.com/gazay/gon/blob/master/README.md
有一个叫做 gon 的优秀 gem 可以简化和组织很多事情:https: //github.com/gazay/gon/blob/master/README.md