我有一个包含四个select2下拉列表的表。 当我克隆该行以复制它时,新行的下拉列表被禁用,我无法点击它们,我必须在代码中添加什么才能激活它们。
HTML表:
<table id="fla_inf" width="100%">
<tbody>
<tr>
<th class="tab_header" colspan="6">Flavors and Additives</th>
</tr>
<tr>
<th class="tab_header_nam">Flavor Brand</th>
<th class="tab_header_nam">Flavor Name</th>
<th class="tab_header_nam">Dropper type</th>
<th class="tab_header_nam">Quantity Unit</th>
<th class="tab_header_nam">Quantity</th>
<th class="tab_header_nam">Add/Remove row</th>
</tr>
<tr class="flavors">
<td>[brand_list]</td>
<td><select id="arome0" class="select2-select"></select></td>
<td><select id="dropper0" class="select2-select">
<option selected="selected" value="type1">type 1</option>
<option value="type2">type 2-3</option>
</select></td>
<td><select id="qtyunit0" class="select2-select">
<option value="ml">ml</option>
<option value="drops">drops</option>
<option selected="selected" value="perc">%</option>
</select></td>
<td><input id="quantity0" class="quantity" type="number" /></td>
<td><input class="addline" src="http://example.org/wp-content/uploads/2015/01/add.png" type="image" /><input class="remline" src="http://example.org/wp-content/uploads/2015/01/delete.png" type="image" /></td>
</tr>
</tbody>
</table>
和jquery代码:
// Add row to the table by cloning existing row
$(document).on('click', '.addline', function(){
var $tr = $(this).closest('tr');
var allTrs = $tr.closest('table').find('tr');
var lastTr = allTrs[allTrs.length-1];
var $clone = $(lastTr).clone();
$clone.find('td').each(function(){
var el = $(this).find(':first-child');
var id = el.attr('id') || null;
if(id) {
var i = id.substr(id.length-1);
var prefix = id.substr(0, (id.length-1));
el.attr('id', prefix+(+i+1));
el.attr('name', prefix+(+i+1));
}
});
$tr.closest('tbody').append($clone);
});
答案 0 :(得分:8)
我试图避免因为这种原因而克隆元素。克隆的替代方法是使用html的模板。
如果要继续克隆,可以在克隆之前取消原始行中的Select2控件的检测,然后重新对其进行检测。
使用.select2('destroy')
函数取消选择Select2控件。
$(document).on('click', '.addline', function () {
var $tr = $(this).closest('tr');
var $lastTr = $tr.closest('table').find('tr:last');
$lastTr.find('.select2-select').select2('destroy'); // Un-instrument original row
var $clone = $lastTr.clone(); // Clone row
$clone.find('td').each(function() { // Alter cloned ids
// ...
});
$tr.closest('tbody').append($clone); // Append clone
$lastTr.find('.select2-select').select2(); // Re-instrument original row
$clone.find('.select2-select').select2(); // Instrument clone
});