【问题标题】:Cloned Select2 is not responding克隆的 Select2 没有响应
【发布时间】:2013-06-15 01:27:11
【问题描述】:

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

代码sn-p:

$(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>

【问题讨论】:

  • 我很瘦,你必须再次在该克隆元素上重新初始化 select2。或者尝试运行带有true 选项的clone,如下所示:clone(true)
  • 感谢您的回复,能否详细说明我尝试重新初始化但仍然没有成功
  • 我试过了还是不行,可能是我的流程不正确,你能解释一下吗
  • 你能解决你的问题吗?会有很大帮助的!

标签: javascript jquery jquery-select2


【解决方案1】:

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

摧毁

还原 Select2 对 DOM 所做的更改。通过 Select2 完成的任何选择都将被保留。

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

克隆行并将其克隆插入 DOM 后,您需要在两个选择元素(原始元素和新克隆的元素)上启用 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();
    });
});

【讨论】:

  • 关于小提琴:如果我选择Master's 选项,它会更改为Doctorate 选项。你能看一下吗?!
  • 感谢详细的解释!注意:select2 移动到适当的 github org 时,小提琴按原样被破坏了。您可以通过更新到https://select2.github.io/select2/select2-3.3.2/select2.jshttps://select2.github.io/select2/select2-3.3.2/select2.css 来修复,还要注意“https”,它(对我而言)可以防止损坏(firefox 会阻止 jsfiddle 等 https 页面上的不安全混合内容)。固定小提琴:jsfiddle.net/nxabgfsv
  • 注意这个fiddle使用select2 3.x;在当前的 4.x 系列中,重复的 ID (#sel) 不再起作用(这也是无效的 HTML),您需要设置 id="",或者将克隆的 ID 更新为唯一。
【解决方案2】:

您必须在克隆之前先销毁 select2,但 .select2('destroy') 不起作用。 使用这个:

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

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

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

【讨论】:

  • 超级令人沮丧,但克隆select2 启用&lt;select&gt;,然后cloned.select2("destroy"); 抛出错误“在未使用 Select2 的元素上调用了 select2('destroy') 方法."...您的解决方案是唯一在我的情况下有效的方法。
【解决方案3】:

我在尝试动态向表中添加一行时遇到了同样的问题。 (该行包含多个 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。 我希望这也适用于其他人。

【讨论】:

  • 谢谢,这在我的用例中有效。另一个要在这里添加的是,我们需要重新初始化 select 的每个实例。
【解决方案4】:

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

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

但这适用于我的情况:

$('.selectpicker').select2('destroy');
$('.selectpicker')
    .removeAttr('data-live-search')
    .removeAttr('data-select2-id')
    .removeAttr('aria-hidden')
    .removeAttr('tabindex');

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

编辑#1

好吧,看来您还必须从正在克隆的元素中删除 ID,因为 select2 尝试在选择中找不到任何 ID 时添加它自己的唯一 ID,但是当您确实选择时,它变得混乱,并且 selet2 仅附加在具有相同 ID 的最后一个元素上。

【讨论】:

  • 我遇到了同样的问题并以几乎相同的方式解决了,还必须清除选项项 id:$(ddls[i]).removeAttr('data-select2-id'); $(ddls[i]).find('option').removeAttr('data-select2-id');
  • @jacvalle - 你拯救了我的一天!作为一个 +,如果你有 optgroups,也从那里删除 id ;)
【解决方案5】:

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

【讨论】:

  • 这从克隆的选择元素中删除了选项
【解决方案6】:

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

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

调用select2 jQuery函数后:

$(".className").select2({               
                placeholder: "Example",
                allowClear:true 
            });

希望对你有所帮助;)

【讨论】:

【解决方案7】:

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

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

【讨论】:

    【解决方案8】:

    什么对我有用,克隆由 select2 管理的选择输入我做了以下操作:
    1.销毁被克隆的select
    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');
    

    【讨论】:

      【解决方案9】:
      //Paste this code after your codes.
      $('span.select2').remove();
      $('select.select2').removeAttr('data-select2-id');
      $('select.select2').select2();
      

      【讨论】:

      • 欢迎来到 SO。通常在答案中添加更多解释,而不仅仅是一段代码。你可以解释你的代码做了什么以及为什么它解决了这个问题。
      【解决方案10】:

      如何使用 joar91 代码。

      var $clone = $("#multiple_objects_with_select2").cloneSelect2();
      
      $($clone ).find('select').select2({
          width:'100%'
      });
      
      $("#some_place").append($clone);
      

      【讨论】:

        【解决方案11】:

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

        【讨论】:

          【解决方案12】:

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

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

          【讨论】:

            【解决方案13】:

            还有一个解决方案:

            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> &nbsp;<a onclick="remove_column(this, 'paste_place');"><i style="font-size: 20px; color: red;" class="icon-minus-circle2"></i></a></td>
            													        </tr>
            													    </tbody>
            													</table>

            【讨论】:

              猜你喜欢
              • 2021-12-02
              • 1970-01-01
              • 2019-04-25
              • 2015-10-20
              • 1970-01-01
              • 2013-11-05
              • 2015-12-01
              • 1970-01-01
              相关资源
              最近更新 更多