将实例变量传递给 js.erb 文件(Rails 3 / jQuery)
我有一个“index.html.erb”文件,其中包含以下内容:
<%= 渲染@users %>
这将呈现“_user.html.erb”并输出一个用于对每个用户执行特定操作的按钮:
<%= link_to "action", action_path(user), :id =>; "#{user.id}_action", :remote =>正确)%>
我已经将我的用户控制器设置为通过查看“action.js.erb”来响应 AJAX 请求。
为了对部分中的特定用户执行 javascript 方法,我想知道如何将部分中的实例变量(例如 user.id)传递到 js.erb 文件中或在 js.erb 文件中访问,例如:
$("#{@user.id}_action").toggle();
I have an "index.html.erb" file with the following:
<%= render @users %>
This renders "_user.html.erb" and outputs a button for performing a certain action on each user:
<%= 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".
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:
$("#{@user.id}_action").toggle();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像在
*.html.erb
文件中一样访问*.js.erb
文件中的信息,使用@users
或控制器中声明的其他实例变量: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:有一个名为 gon 的优秀 gem 可以大大简化和组织事情:
https://github.com/gazay/gon/blob/master/README.md
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