Javascript的局部(Ruby on Rails的) [英] Javascript in partial (Ruby on Rails)
问题描述
例如我有很多意见呈现担任这个职务。
For example i have many comments rendered for the post.
<%= render post.comments %>
和在评论部分我了JavaScript至极会重复很多次,我有多少意见有
And in comments partial i have javascript wich will repeated so many times how many comments i have
_comment.html.erb
<div id="content_<%= comment.id %>"><%= comment.content %></div>
<script>$("content_<%= comment.id %>").click(function() { alert('content of comment <%= comment.id %>') });</script>
什么是避免源$ C $ C重复的JavaScript的最好方法是什么? 我试图创建* _comment.js.erb *文件,并把JavaScript的存在,但我不知道如何使它发挥作用。
What is the best way to avoid repeating javascript in source code? I tried to create *_comment.js.erb* file and put javascript there, but i don't understand how to make it work.
任何人都可以请解释我如何解决这个问题?
Can anyone please explain me how to solve this problem?
推荐答案
您可以更改实施有下的应用程序/资产/ JavaScript的一个js文件里面你的脚本。改变脚本的选择器类的意见,而不是唯一的ID相匹配。如果需要的话,可以使用,而不是因为你现在做的服务器上做这个JavaScript来读取元素的内容。
You can change the implementation to have a single js file under app/assets/javascripts with your script inside. change the selector of the script to match the class of the comments instead of a unique ID. If required, use javascript to read the content of elements, instead of doing this on the server as you do now.
这篇关于Javascript的局部(Ruby on Rails的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!