jQuery 克隆的 Select2 没有响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17175534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cloned Select2 is not responding
提问by Abs
I am trying to clone a row which contains select2 tool ,when i clone that row using jQuery the cloned select2 is not responding.In image given below first select2 which is original is working fine but 2nd and 3rd select2 which are cloned not responding
我正在尝试克隆包含 select2 工具的一行,当我使用 jQuery 克隆该行时,克隆的 select2 没有响应。
code snippet:
代码片段:
$(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>
回答by Zabbala
Before you clone the row, you need to disable Select2 on the select element by calling its destroy
method:
在克隆该行之前,您需要通过调用其destroy
方法来禁用 select 元素上的 Select2 :
destroy
Reverts changes to DOM done by Select2. Any selection done via Select2 will be preserved.
破坏
还原 Select2 对 DOM 所做的更改。通过 Select2 完成的任何选择都将被保留。
See http://ivaynberg.github.io/select2/index.html
见http://ivaynberg.github.io/select2/index.html
After you clone the row and insert its clone in the DOM, you need to enable select2 on both select elements (the original one and the new cloned one).
克隆该行并将其克隆插入 DOM 后,您需要在两个选择元素(原始元素和新克隆的元素)上启用 select2。
Here's a JSFiddle that shows how it can be done: http://jsfiddle.net/ZzgTG/
这是一个 JSFiddle,展示了如何完成:http: //jsfiddle.net/ZzgTG/
Fiddle's code
小提琴的代码
HTML
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
CSS
#contents div.select2-container {
margin: 10px;
display: block;
max-width: 60%;
}
jQuery
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();
});
});
回答by amxa
you have to destroy select2 first before cloning, but .select2('destroy') not works. Use this:
您必须在克隆之前先销毁 select2,但 .select2('destroy') 不起作用。用这个:
$myClone = $("section.origen").clone();
$myClone.find("span").remove();
$myClone.find("select").select2();
$("div").append($myClone);
回答by eheydenr
I faced the same problem, while trying to add a row to a table dynamically. (the row contains more than one select2 instance.)
我在尝试动态向表中添加一行时遇到了同样的问题。(该行包含多个 select2 实例。)
I solved it in this way:
我是这样解决的:
function addrow()
{
var row = $("#table1 tr:last");
row.find(".select2").each(function(index)
{
$(this).select2('destroy');
});
var newrow = row.clone();
$("#table1").append(newrow);
$("select.select2").select2();
}
The trick was that you need to destroy all the instances of .select2 separately and before cloning the row. And then after cloning, re-initialize the .select2. I hope this will work for others as well.
诀窍是您需要在克隆行之前分别销毁 .select2 的所有实例。然后克隆后,重新初始化.select2。我希望这也适用于其他人。
回答by Volmarg Reiso
I've actually created account to answer this, since it took me a while to make it work.
我实际上已经创建了帐户来回答这个问题,因为我花了一段时间才让它工作。
This is not working when used before cloning:
$('.selectpicker').select2('destroy')
这在克隆前使用时不起作用:
$('.selectpicker').select2('destroy')
But this works in my case:
但这在我的情况下有效:
$('.selectpicker').select2('destroy');
$('.selectpicker')
.removeAttr('data-live-search')
.removeAttr('data-select2-id')
.removeAttr('aria-hidden')
.removeAttr('tabindex');
Just remove all the additional attributes which select2 adds.
只需删除 select2 添加的所有附加属性。
Edit #1
编辑 #1
Ok so seems like You also got to remove ID from the element that is being cloned since select2 tries to add it's own unique id when none is found on the select, but when You do have select it's getting messy and selet2 attaches only on the last element with the same ID.
好的,看来您还必须从正在克隆的元素中删除 ID,因为 select2 尝试添加自己的唯一 id,但当您没有在 select 上找到时,它会变得混乱,而 selet2 仅附加在最后一个具有相同 ID 的元素。
回答by Abhinav bhardwaj
you have to destroy all select2 first before cloning for example:
您必须在克隆之前先销毁所有 select2,例如:
var div = $("#filterForm div");
//find all select2 and destroy them
div.find(".select2").each(function(index)
{
if ($(this).data('select2')) {
$(this).select2('destroy');
}
});
//Now clone you select2 div
$('.filterDiv:last').clone( true).insertAfter(".filterDiv:last");
//we must have to re-initialize select2
$('.select2').select2();
回答by jorar91
I solved this by creating a different clone function:
我通过创建一个不同的克隆函数解决了这个问题:
jQuery.fn.cloneSelect2 = function (withDataAndEvents, deepWithDataAndEvents) {
var $oldSelects2 = this.is('select') ? this : this.find('select');
$oldSelects2.select2('destroy');
var $clonedEl = this.clone(withDataAndEvents, deepWithDataAndEvents);
$oldSelects2.select2();
$clonedEl.is('select') ? $clonedEl.select2() :
$clonedEl.find('select').select2();
return $clonedEl;
};
回答by praguan
I solved this problem with it:
Call destroy method before you add new row
我用它解决了这个问题:
在添加新行之前调用 destroy 方法
$(".className").select2("destroy"); //Destroy method , connect with class no ID (recomend)
After it call select2 jQuery function:
在它调用 select2 jQuery 函数之后:
$(".className").select2({
placeholder: "Example",
allowClear:true
});
hope it helps ;)
希望能帮助到你 ;)
回答by husky
What worked for me, to clone select input managed by select2 I did the following:
1. Destroy the select that is cloned
2. Clone with a true param
3. Remove from the clone attributes 'id' and 'data-select2-id'
4. Remove attribute 'data-select2-id' from every option in the clone
5. Re-initialize element that was cloned
6. Initialize cloned element resetting the value
什么对我有用,克隆由 select2 管理的选择输入我做了以下事情:
1. 销毁被克隆的选择
2. 使用真正的参数
克隆 3. 从克隆属性中删除“id”和“data-select2-id”
4. 从克隆中的每个选项中删除属性 'data-select2-id'
5. 重新初始化被
克隆的元素 6. 初始化被克隆的元素重置值
Here is an example:
下面是一个例子:
const origin = $('select').last(); // last in case there are more than one select
origin.select2('destroy');
const cloned = origin.clone(true);
cloned.removeAttr('data-select2-id').removeAttr('id');
cloned.find('option').removeAttr('data-select2-id');
origin.select2();
cloned.select2().val(null).trigger('change');
回答by Metehan NetADIM
//Paste this code after your codes.
$('span.select2').remove();
$('select.select2').removeAttr('data-select2-id');
$('select.select2').select2();
回答by Ramas Win
And one more solution:
还有一种解决方案:
function add_column(copy, paste) {
$("." + copy + ":first").clone().appendTo("." + paste);
$("." + paste + " tr:last input").val('');
$("." + paste + " tr:last select").val('');
// and etc...
// Initialize
$("." + paste + " tr:last select").select2({
language: {
inputTooShort: function() {
return 'Pra?ome ?vesti bent vien? raid? paie?kai';
}},
ajax: {
url: base_url+"fuel/Fuel/getWorkersSelect",
type: 'POST',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
$("." + paste + " tr:last select").last().next().next().remove();
}
function remove_column(e, paste) {
var how = $("." + paste + " tr").length;
if (how >= 2) {
$(e).parent().parent().remove();
} else {
$("." + paste + " input").val('');
$("." + paste + " select").val('');
// and etc...
}
}
<table class="table table-striped table-bordered">
<thead>
<tr>
<th width="15%">Ma?ina</th>
<th width="15%">I?duota</th>
<th width="15%">Gr??inta</th>
<th width="20%">Vairuotojas</th>
<th width="10%">Neaktualus</th>
<th width="15%">Perdavimo aktas</th>
<th width="10%">Veiksmai</th>
</tr>
</thead>
<tbody class="paste_place">
<tr class="copy_item">
<td><input type="text" name="masina[]" class="form-control" placeholder="?veskite..." /></td>
<td><input type="text" name="isduota[]" class="form-control datepicker" placeholder="?veskite..." /></td>
<td><input type="text" name="grazinta[]" class="form-control datepicker" placeholder="?veskite..." /></td>
<td>
<select class="form-control select-remote-vairuotojai" name="vairuotojas[]">
<option value="">Pasirinkite i? s?ra?o</option>
</select>
</td>
<td><input type="text" name="neaktualus[]" class="form-control" placeholder="?veskite..." /></td>
<td>haha</td>
<td><a onclick="add_column('copy_item', 'paste_place');"><i style="font-size: 20px;" class="icon-plus-circle2"></i></a> <a onclick="remove_column(this, 'paste_place');"><i style="font-size: 20px; color: red;" class="icon-minus-circle2"></i></a></td>
</tr>
</tbody>
</table>