gpt4 book ai didi

javascript - 克隆的 Select2 没有响应

转载 作者:行者123 更新时间:2023-11-28 02:33:14 25 4
gpt4 key购买 nike

我正在尝试克隆包含 select2 工具的行,当我使用 jQuery 克隆该行时,克隆的 select2 没有响应。在下面给出的第一个 select2 原始图像中工作正常,但第二个和第三个 select2 没有被克隆回应

代码片段:

$(document).ready(function() {
var clonedRow = $('.parentRow').clone().html();
var appendRow = '<tr class = "parentRow">' + clonedRow + '</tr>';
$('#addRow').click(function() {
$('#test').after(appendRow);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class="parentRow" id="test">
<td>
<g:message code="educationDetails.educationLevel.label" default="Education Level" />
</td>
<td>
<div style="float: left;">
<g:select name="degree.id" from="${EducationalDegree.list()}" optionKey="id" optionValue="title" noSelection="['': '']" id="degree" value="${cvEducationDetailCO?.degree?.id}" onchange="changeGradeSelectData(this.value)" />
</div>
<div>
<a href="javascript:void(0)" id="addRow">
<img alt="" title="Add Additional Education Level" src="/static/images
/top_submit_1.gif">
</a>
</div>
</td>
</tr>

最佳答案

在克隆该行之前,您需要通过调用其 destroy 方法来禁用 select 元素上的 Select2:

destroy

Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.

参见 http://ivaynberg.github.io/select2/index.html

克隆该行并将其克隆插入 DOM 后,您需要在两个选择元素(原始元素和新克隆元素)上启用 select2。

这里有一个 JSFiddle 展示了它是如何完成的:http://jsfiddle.net/ZzgTG/

Fiddle 的代码

HTML

<div id="contents">
<select id="sel" data-placeholder="-Select education level-">
<option></option>
<option value="a">High School</option>
<option value="b">Bachelor</option>
<option value="c">Master's</option>
<option value="c">Doctorate</option>
</select>
</div>
<br>
<button id="add">add a dropdown</button>

CSS

#contents div.select2-container {
margin: 10px;
display: block;
max-width: 60%;
}

jQuery

$(document).ready(function () {
$("#contents").children("select").select2();
$("#add").click(function () {
$("#contents")
.children("select")
// call destroy to revert the changes made by Select2
.select2("destroy")
.end()
.append(
// clone the row and insert it in the DOM
$("#contents")
.children("select")
.first()
.clone()
);
// enable Select2 on the select elements
$("#contents").children("select").select2();
});
});

关于javascript - 克隆的 Select2 没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com