按钮,使用javascript将该表单块附加到整个表单中

Button in a form, to append that chunk of form to overall form using javascript

本文关键字:表单 javascript 使用 按钮      更新时间:2023-09-26

表单中的按钮,使用javascript将该表单块附加到整个表单中。

我在html.erb文件中的这行代码中做错了什么?

<%= button_to "Add Another Record", '$('.records-container').append('<%=j render partial: 'records/form'%>');'%> 

button_to不会做你认为它会做的事情:)

如果你真的想使用内联javascript,你可以做一些类似的事情

link_to 'Add another record', '#', onclick: "$(..).append(..); return false;"

但说实话:我们尽量避免那种javascript编程风格。因此,替代方法:

link_to 'Add another record', '#', 
   'data-template' => CGI.escapeHTML(render('records/form').to_str).html_safe

并在您的javascript中添加以下内容:

$(document).on('click', 'a[data-template]', function(e) {
  e.preventDefault();
  var $this     = $(this),
      content   = $this.data('template');
  $('.records-container').append(content);
)

这是茧中使用的代码的简单版本(未经测试),茧是构建嵌套表单的宝石。然而,如果你试图构建嵌套表单,我建议你检查一下co茧(因为在这种情况下,你至少还需要为每个新的嵌套表单创建唯一的id)