Table 带 select2 框的行克隆会创建另一个 select 框

Table row cloning with select2 box creates another select box

我正在尝试克隆一个 table 行,其中包含一个 select2 select 框。

<table class="table" id="req_table">
  <thead>
    <tr>
      <th class="col-md-2">Item</th>
      <th class="col-md-2">Store Description</th>
      <th class="col-md-2">Measurement Unit</th>
      <th class="col-md-1">Quantity Demanded</th>
      <th class="col-md-1">Rate</th>
      <th class="col-md-1">Stock In Hand</th>
      <th class="col-md-3">Remarks(If Any)</th>
    </tr>
  </thead>

  <tbody>
    <tr class="tr_clone">
      <td class="col-md-2">{!! Form::select('item_measurement_id[]', $item_measurements, null, ['class' => 'select2 required col-md-12 item_measurement', 'id' => 'item_measurement_id', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
      <td class="col-md-2">{!! Form::textarea('store_description[]', null, ['class' => 'form-control required', 'id' => 'store_description', 'cols' => 3, 'rows' => 2, 'placeholder' => 'Description of Stores', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
      <td class="col-md-2">{!! Form::select('measurement_unit_id[]', $units, null, ['class' => 'required form-control col-md-12', 'id' => 'measurement_unit_id', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
      <td class="col-md-1">{!! Form::number('quantity_demanded[]', null, ['class' => 'form-control required', 'id' => 'quantity_demanded', 'step' => '0.01', 'placeholder' => 'Quantity Demanded', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
      <td class="col-md-1">{!! Form::number('rate[]', null, ['class' => 'rate form-control required', 'id' => 'rate', 'placeholder' => 'Rate', 'readonly' => true, 'step' => '0.01', 'autocomplete' => 'off', 'required' => 'true']) !!}</td>
      <td class="col-md-1"><div class="col-md-3 stock_in_hand" style="margin-top:4px">0</div>
      </td>
      <td class="col-md-3">{!! Form::textarea('remarks[]', null, ['class' => 'form-control required', 'id' => 'remarks', 'rows' => 2, 'placeholder' => 'Remarks if any', 'autocomplete' => 'off',]) !!}</td>
    </tr>
  </tbody>
</table>

javascript 是:

$('.add_more_item').click(function(e) {

    $latest_tr  = $('#req_table tr:last');
    $clone          = $latest_tr.clone();

    $('select.select2').select2('destroy');
    $latest_tr.after($clone);
    $('select.select2').select2();
    $clone.find(':text').val('');
    item++;
    show_hide_item(item);
})

当我克隆该行时,它会创建另一个 select2 框以及 select 字段。当我点击添加按钮时,这个过程会继续。如何删除多余的字段?

Fiddle

您 运行 $('select.select2').select2('destroy'); 克隆行后。 只需将该行移动到 $clone = $latest_tr.clone();:

之前
$('select.select2').select2('destroy');

$clone = $latest_tr.clone();

已更新 fiddle:https://jsfiddle.net/etgf979x/