jquery Select2 destroy在fiddle上有效,但在另一台服务器上无效

7fhtutme  于 2023-04-29  发布在  jQuery
关注(0)|答案(1)|浏览(288)

这个问题似乎很奇怪,但这就是我所面临的。有2个下拉菜单的表,其中附加了select2。我们应该在克隆它之前销毁select2,然后再次使用它,这是我在代码中所做的。因此,代码可以在fiddle上工作:http://jsfiddle.net/cwp2d7gq/1/但是,相同的代码在此链接上不起作用:https://gicrerd.com/utilitaire/test
有人知道这是什么问题吗?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
<table class="table table-sm table-striped mb-0">
<thead>
<tr class="bg-th">
<th>
Country
</th>
<th scope="col">
Towns
</th>

</tr>
</thead>

<tbody>
<tr>
<td>
<select class="form-select" onChange="center_area_on_change(this);">
<option value=""></option>
<option>Country 1</option>
<option>Country 2</option>
<option>Country 3</option>
<option>Country 4</option>
</select>
</td>
<td style="width:280px;display:block">

<select style='width:100%' onChange="getTarifDataSeguroPrivado(this);">
<option></option>
<option>Town 1</option>
<option>Town 2</option>
<option>Town 3</option>
<option>Town 4</option>
<option>Town 5</option>
</select>

</td>

</tr>
</tbody>
</table>

Jquery

function center_area_on_change (el) {
console.log(el);
}


function getTarifDataSeguroPrivado(dropDown) {
addRow();
}

function addRow() {
$('table select').select2('destroy');
var tableBody = $('table').find("tbody");
var trLast = tableBody.find("tr:last");
var trNew = trLast.clone();

const lastSelectedCountryIndex = trLast.find('select').eq(0).find('option:selected').index();

trNew.find('select').eq(0).find('option').eq(lastSelectedCountryIndex).prop('selected', true);

trLast.after(trNew);
$('table select').select2();
}

$('table select').select2();
a7qyws3x

a7qyws3x1#

我相信这个问题是由于你复制了你的HTML元素ID。HTML元素ID必须唯一;但是每次克隆和追加一行时,都为该行和两个选择元素创建了重复的ID。我建议不要在任何克隆的元素中使用ID。

相关问题