克隆的Select2没有响应

时间:2013-06-18 17:46:34

标签: javascript jquery jquery-select2

我正在尝试克隆包含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>

13 个答案:

答案 0 :(得分:53)

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

  

<强>破坏

     

恢复由Select2完成的DOM更改。通过Select2完成的任何选择都将被保留。

请参阅http://ivaynberg.github.io/select2/index.html

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

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

小提琴的代码

<强> 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();
    });
});

答案 1 :(得分:8)

你必须在克隆之前首先销毁select2,但是.select2('destroy')不起作用。 使用此:

$myClone = $("section.origen").clone();

$myClone.find("span").remove();
$myClone.find("select").select2();

$("div").append($myClone);

答案 2 :(得分:3)

你必须在克隆之前先销毁所有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(); 

答案 3 :(得分:2)

我通过创建一个不同的克隆函数来解决这个问题:

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;
};

答案 4 :(得分:2)

我用它解决了这个问题:
在添加新行之前调用destroy方法

<span style="-webkit-line-box-contain: block inline replaced">A</span>

调用select2 jQuery函数后:

 $(".className").select2("destroy");  //Destroy method , connect with class no ID (recomend)

希望它有所帮助;)

答案 5 :(得分:2)

我在尝试动态地向表中添加行时遇到了同样的问题。 (该行包含多个select2实例。)

我用这种方式解决了它:

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();
}

诀窍是你需要在克隆行之前分别销毁.select2的所有实例。然后在克隆之后,重新初始化.select2。 我希望这也适用于其他人。

答案 6 :(得分:1)

我实际上创建了一个帐户来回答这个问题,因为我花了一段时间才能让它发挥作用。

在克隆之前使用时这不起作用: $('.selectpicker').select2('destroy')

但这适用于我的情况:

$('.selectpicker').select2('destroy')

只需删除select2添加的所有其他属性。

编辑#1

好吧好像你还要从正在克隆的元素中删除ID,因为当select2尝试添加它时,如果没有找到它的唯一ID,那么当你确实选择了它时#39 ; s变得混乱,selet2只附加在具有相同ID的最后一个元素上。

答案 7 :(得分:0)

如何使用jorar91代码。

var $clone = $("#multiple_objects_with_select2").cloneSelect2();

$($clone ).find('select').select2({
    width:'100%'
});

$("#some_place").append($clone);

答案 8 :(得分:0)

在父级div中,不要在其上应用select2。首先克隆它并将其保存在变量中然后应用select2。稍后在原点上应用select2(因为没有select2的原始保存在变量中)然后应用于新创建的选择。  我试过这种方式,它正在运作

答案 9 :(得分:0)

我提议做这个,这是我的简单例子:

function copy_row(id) {
    var new_row = $("#"+id+" tbody tr:first").clone();
    $("#"+id+" tbody").append('<tr>'+new_row.html()+'</tr>');
    $("#"+id+" tbody tr:last input").val('');
    $("#"+id+" tbody tr:last select").val('');
    $("#"+id+" tbody tr:last input[type='checkbox']").prop('checked', false);

    // Initialize
    $(".select-remote-address:last, .select-remote-address2:last").select2({
        language: {
            inputTooShort: function() {
            return 'Įveskite...';
        }},
        ajax: {
            url: base_url+"index.php/orders/data/getAddress",
            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
    });

    $(".select-remote-address:last").last().next().next().remove();
    $(".select-remote-address2:last").last().next().next().remove();

    // Datetimepicker
    jQuery('.date_1:last, .date_2:last').datetimepicker({
      i18n:{
        lt:{
         months:[
          'Sausis','Vasaris','Kovas','Balandis',
          'Gegužė','Birželis','Liepa','Rugpjūtis',
          'Rugsėjis','Spalis','Lapkritis','Gruodis',
         ],
         dayOfWeek:[
          "Pir", "An", "Tre", "Ket",
          "Pen", "Šeš", "Sek",
         ]
        }
       },
      format:'Y-m-d H:i',
    });
}

答案 10 :(得分:0)

还有另一种解决方案:

export CORE_PEER_MSPCONFIGPATH=<path to admin msp>
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...
    }
}

答案 11 :(得分:0)

什么对我有用,克隆由select2管理的选择输入,我做了以下工作:
1.销毁克隆的选择
2.克隆真实的参数
3.从克隆属性“ id”和“ data-select2-id”中删除
4.从克隆中的每个选项中删除属性“ data-select2-id”
5.重新初始化克隆的元素
6.初始化克隆的元素以重置值

这里是一个例子:

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');

答案 12 :(得分:0)

//Paste this code after your codes.
$('span.select2').remove();
$('select.select2').removeAttr('data-select2-id');
$('select.select2').select2();
相关问题