jQuery表单转发器和select2不能一起工作

我正在使用Select2和jQuery表单转发器( https://github.com/DubFriend/jquery.repeater )

我已经在google /上搜索了2天,但似乎无法让它工作。

include jquery/select2.js/jquery.repeater.js var form = $('#form'); form.find('select').select2(); form.repeater({ show: function () { $(this).show(function(){ form.find('select').select2('destroy').select2(); }); }, hide: function (remove) { $(this).hide(remove); } }); 

问题是jQuery.repeater克隆了div标签,其中input2已经初始化并且已经更改了DOM,因此jQuery.repeater会复制更改的DOM。 我试图在调用重复动作之前销毁select2,但是dindt也可以工作。

我是SO的新手,但是很长一段时间的读者。 我正在开发一个项目,我使用jQuery.repeater重复多个select2输入。 以下方法有助于解决我在加载后初始化输入的问题。

 $('.job_repeater').repeater({ show: function () { $(this).slideDown(); $('.select2-container').remove(); $('Replace with your select identifier id,class,etc.').select2({ placeholder: "Placeholder text", allowClear: true }); $('.select2-container').css('width','100%'); }, hide: function (remove) { if(confirm('Confirm Question')) { $(this).slideUp(remove); } } }); 

更精确的jQuery选择器将有助于仅删除/初始化您想要的选择。

我初始化select2后使用的CSS行总是调整父div /容器的宽度。

最好的祝福

试试这个

 include jquery/select2.js/jquery.repeater.js var form = $('#form'); form.find('select').select2(); form.repeater({ show: function () { $(this).show(function(){ // you have not really created this second one // so the destroy does not work. // Since it is just a copy of the html, form.find('select').next('.select2-container').remove(); form.find('select').select2(); }); }, hide: function (remove) { $(this).hide(remove); } }); 

这是一个在表格中继器按钮时钟初始化select2的解决方案。

  

有关问题和解决方案的深入概述, 请参见此处

使用initEmpty: false选项时,在show函数中初始化select2对第一行不起作用。 在这种情况下,您还可以在ready函数运行时初始化select2。

 $('.repeater').repeater({ isFirstItemUndeletable: false, initEmpty: false, ready: function () { $('.select2').select2({ placeholder: "Select an option...", }); }, show: function () { $(this).slideDown(); $('.select2').select2({ placeholder: "Select an option...", }); }, hide: function () { $(this).slideUp(); }, }); 

我通过首先在文档准备好初始化原始select2然后使用$ this在repeater show方法上重复selected2元素的每个实例进行目标来解决它。 例如,如果您有一个简单的选择下拉列表和多个选择,您的代码应如下所示:

 $(document).ready(function () { $(".select2").select2({ placeholder: "Select a state", allowClear: true }); }); $('.repeater').repeater({ show: function () { $(this).slideDown(); $(this).find('.select2-multiple').select2({ placeholder: "Select Title", allowClear: true, }); $(this).find('.select2').select2({ placeholder: "Select Title", allowClear: true, }); }, hide: function (deleteElement) { if (confirm('Are you sure you want to delete this element?')) { $(this).slideUp(deleteElement); } } });