2

例如,我为该帖子提供了许多评论。

<%= render post.comments %>

在部分评论中,我有javascript,它会重复很多次我有多少评论

_comment.html.erb

<div id="content_<%= comment.id %>"><%= comment.content %></div>
<scr​ipt>$("content_<%= comment.id %>").click(function() { a​lert(​'content of comment <%= comment.id %>'​) });</sc​ript>

避免在源代码中重复 javascript 的最佳方法是什么?我试图创建 *_comment.js.erb* 文件并将 javascript 放在那里,但我不明白如何使它工作。

谁能解释一下如何解决这个问题?

4

1 回答 1

3

您可以将实现更改为在 app/assets/javascripts 下拥有一个带有脚本的 js 文件。更改脚本的选择器以匹配评论的类而不是唯一的 ID。如果需要,请使用 javascript 来读取元素的内容,而不是像现在这样在服务器上执行此操作。

于 2012-07-07T16:23:51.590 回答