javascript - 如何点击编辑列表项?使用 AJAX、jQuery、Rails4

标签 javascript jquery ruby-on-rails ajax jquery-events

目前,我可以通过单击“编辑”链接来编辑列表项。

但是,我希望能够仅单击列表项即可对其进行编辑。

这是我的 _item.html.erb 部分。一个项目有很多项,这就是我使用 id="<%= dom_id(item) 的原因:

<li class="klikkaa" id="<%= dom_id(item) %>">
    <%= item.description %>
    <%= link_to 'Edit', edit_project_item_path(item.project, item), remote: true %>
</li>  

编辑.js.erb:

$('#<%= dom_id(@item)%>').html("<%= j (render 'editform') %>");

我尝试在 asset/javascripts/item.js 中执行以下操作:

 $(document).ready(function(){
       $('.klikkaa').click(function(){
          $('#<%= dom_id(@item)%>').html("<%= j (render 'editform') %>");
       });
 });

但是,我在控制台上收到错误:

"Uncaught Error: Syntax error, unrecognized expression: #<%= dom_id(@item)%>"

如何在单击列表项本身而不是单击“编辑”链接时编辑列表项?

最佳答案

如果您想在 JS 中使用 Rails 中的变量和值,您应该将 js 文件的名称更改为 item.js.erb

来自 Rails guide 的示例其中展示了如何使用 Rails 助手 (asset_path)

If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code:

$('#logo').attr({ src: "<%= asset_path('logo.png') %>" });

关于javascript - 如何点击编辑列表项?使用 AJAX、jQuery、Rails4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28430768/

相关文章:

ruby-on-rails - Rails has_many :through with collection_select form helper

javascript - 通过 Javascript 代码单击 HTML 表单的提交按钮

javascript - 使用 Javascript 在服务器 URL 上发布 JSON 数据

javascript - 将元素从一个对象添加/合并到数组内的另一个对象

javascript - 如何: Dynamically move Google Gauge?

jquery - 在浏览器中显示 Webdis 响应

jquery - 显示隐藏不透明的div

javascript - application.js 中的代码未在 Rails 中加载

JQuery循环.mouseenter动画不停止

ruby-on-rails - OmniAuth 单点登录与设计,invalid_credentials