Javascript in partial (Ruby on Rails)

Javascript in partial (Ruby on Rails)

本文关键字:on Rails Ruby in partial Javascript      更新时间:2023-09-26

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

<%= 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,但我不知道如何使其工作。

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

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