在克隆 select2 的 select 事件中

On select event for a cloned select2

为了在克隆的 select2 上监听 select2:select,我需要采取哪些额外步骤?

我试过.clone(true)$('.myclass').select2('destroy');开头的点击功能,用$('#table tbody').hide().show(0);刷新DOM。

这似乎是基于此 GitHub 问题的推荐方法。

https://github.com/select2/select2/issues/2522

$('.myclass').select2();

$('.myclass').on('select2:select', function(e) {
 alert('foo');
});

$('#addRow').click(function() {
  $('#table tbody').append($('#table tbody tr:last').clone());
  $('#table tbody tr:nth-last-child(2) select').addClass('myclass');
  $('.myclass').select2();  
});
.hidden {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<table id="table">
 <thead></thead>
 <tbody>
   <tr>
     <td>
      <select class="myclass">
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select> 
     </td>
   </tr>
   <tr>
     <td>
       <select id="clone" class="hidden">
        <option>1</option>
        <option>2</option>
        <option>3</option>
       </select>
     </td>
   </tr>
 </tbody>
 <tfoot>
  <button id="addRow">
    Add Row 
  </button>
 </tfoot>
</table>

您可以 event delegation 将事件绑定到动态添加的元素。

$('.myclass').select2();

$(document).on('select2:select','.myclass', function(e) {
 alert('foo');
});

$('#addRow').click(function() {
  $('#table tbody').append($('#table tbody tr:last').clone());
  $('#table tbody tr:nth-last-child(2) select').addClass('myclass');
  $('.myclass').select2();  
});
.hidden {
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<table id="table">
 <thead></thead>
 <tbody>
   <tr>
     <td>
      <select class="myclass">
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select> 
     </td>
   </tr>
   <tr>
     <td>
       <select id="clone" class="hidden">
        <option>1</option>
        <option>2</option>
        <option>3</option>
       </select>
     </td>
   </tr>
 </tbody>
 <tfoot>
  <button id="addRow">
    Add Row 
  </button>
 </tfoot>
</table>