好的,这里有几个问题:
- 您没有将
div 替换绑定到事件?
- 您在
front-end javascript 中使用ERB 代码(仅适用于ajax 调用)
对于每个按钮点击我想注入一些 html.erb 部分
这里有两个选项是通过ajax 调用部分(仅在您有动态部分时才推荐)或在helper 方法或其他方法中预加载部分...
我将详细介绍这两种方法。
--
Ajax
如果您的部分有 动态 内容(IE 填充有变量或类似内容),您需要通过 Ajax 传递请求。
这是因为 Ruby 只能处理服务器上的<%= ERB %> 代码。由于 Javascript 是客户端,您必须使用 ajax 将 异步 请求传递到您的服务器,这将为您呈现 JS。
Rails UJS 引入了remote 标签——这消除了这个过程中的很多麻烦:
#app/view/controller/your_current_view.html.erb
<%= link_to "your post", your_current_view_path, remote: true %>
#app/controllers/controller.rb
class Controller < ApplicationController
respond_to :js, :html #-> will need the responders gem after Rails 4
def your_current_view_path
....
end
end
这将允许您使用来自服务器的以下js.erb 文件:
#app/views/controller/your_current_view.js.erb
$('#my_div').append('<%=j render "shared/my_partial" %>');
这将允许您使用您在操作中设置的部分和任何@instance_variables。
--
独立 JS
如果您的partial 是“静态的”(不需要任何动态数据),您将能够使用以下内容:
#app/views/controller/your_current_view.html.erb
<%= content_tag :div, class: "hidden" do %>
<%= render "shared/my_partial" %>
<% end %>
这将允许您使用以下 JS:
#app/assets/javascripts/application.js
$("a.link").on("click", function(e){
e.preventDefault();
hidden = $(".hidden").html();
$("div").html(hidden);
});