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

时间:2017-02-16 15:46:24

标签: javascript ruby-on-rails select2

当我克隆新行"下拉菜单工作时,

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);
  }**

1 个答案:

答案 0 :(得分:0)

在克隆行之前必须销毁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();
}