具有功能的Cocoon数据关联插入节点

时间:2017-03-10 02:32:13

标签: javascript jquery html ruby-on-rails cocoon-gem

根据https://github.com/nathanvda/cocoon#link_to_add_association,您应该可以将功能传递给data-association-insertion-node

我试过这个:

<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'get_row()'} %>

而且:

<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'get_row'} %>

而这(绝望):

<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'function get_row(node){var row = "<tr></tr>";$("#table_body").append(row);return row;}'} %>

但它们都不起作用。

使用Javascript:

function get_row(node){
    var row = "<tr></tr>"
    $("#table_body").append(row);
    return row
}

我正在尝试向tr添加table,然后将嵌套的时间段表单附加到tr

1 个答案:

答案 0 :(得分:3)

目前,您无法做到这一点。像这样设置data-association-insertion-method时,它只是javascript中的字符串,而不是对方法的引用。

在README中作为documented,您必须执行以下操作(假设您为链接指定了类.add-timeslot):

$(document).on('turbolinks:load', function() {
  $(".add-timeslot a").
    data("association-insertion-method", 'append').
    data("association-insertion-node", function(link){
      return link.closest('.row').next('.row').find('.sub_tasks_form')
    });
});

(该示例几乎是逐字逐句从文档中复制出来仅用于演示目的 - 您必须填写get_row函数)