select2 停止为克隆的行工作,为什么?

select2 stop working for the cloned rows, why?

当我克隆新行时 Select2 停止工作“下拉菜单工作 仅适用于第一行(默认行)”克隆的下拉菜单 那些不工作。这是我的代码:

**= f.inputs 'Items not in inventory' do
    %table
      %thead
        %td{style: 'width: 20%; padding-left: 20px;'}
          %b Select Product
        %td{style: 'max-width: 70px;'}
          %b Repossessed Inventory (Serial/Amount)

      %tbody{id: 'tableToModify'}
        %tr{id: 'rowToClone'}
          = semantic_fields_for :other_stuff do |os|
            %td{style: 'padding-left: 20px;'}
              = os.input :product_id, as: :select, label: false, collection: Product.all.order(:name).pluck(:name, :id), input_html: {class: 'select2'}
            %td
              = os.input :repossessed, label: false, input_html: { style: 'width: 100px;' }
              %td

                = link_to "x", "javascript:if ($('#tableToModify tr').length > 1) {document.getElementById('tableToModify').deleteRow($('#tableToModify tr').length - 1);}"

    = link_to 'Add item', 'javascript:cloneRow()'
    = f.input :rest_is_lost, as: :boolean, label: 'Mark unrepossessed items as lost', input_html: { checked: 'checked' }

  = f.actions do
    = f.action :submit, label: 'Create Repossession Case'
    = f.action :cancel, label: 'Cancel', button_html: { href: url_for(action: :index) }, wrapper_html: { class: :cancel }

:javascript
  function cloneRow(){
    var row = document.getElementById("rowToClone");
    var table = document.getElementById("tableToModify");
    var clone = row.cloneNode(true);
    var numberOfRows = document.getElementById("tableToModify").rows.length;
    clone.id = numberOfRows + 1;
    table.appendChild(clone);
  }**

您必须先销毁 select2,然后再克隆该行然后再次绑定它:

function cloneRow(){
  var row = document.getElementById("rowToClone");
  var table = document.getElementById("tableToModify");

  $(table).find('select').select2('destroy');

  var clone = row.cloneNode(true);
  var numberOfRows = document.getElementById("tableToModify").rows.length;
  clone.id = numberOfRows + 1;
  table.appendChild(clone);

  $(table).find('select').select2();
}