如何打开新克隆的Bootstrap选择字段?

时间:2018-11-19 21:11:35

标签: javascript jquery twitter-bootstrap bootstrap-4 bootstrap-select

我正在尝试克隆引导选择字段,并立即打开克隆。

下面的代码切换原始选择字段。

$('.selectpicker').selectpicker("toggle");

但是,当我尝试切换克隆字段时,只选择了克隆字段,而不打开它。

此处的示例:http://jsfiddle.net/jh4wztab/4/

如何在克隆后立即打开克隆的引导程序选择?

HTML

<div id="jurisdictionpicker">
  <select class="selectpicker jurisdiction" data-live-search="true" data-size="8" id="jurisdiction_">
    <option>Philly</option>
    <option>DC</option>
    <option>New York</option>
  </select>
</div>

<BR><BR><BR><BR><BR><BR><BR><BR>

<button id="clonejurisdiction">Clone</button>
<B>Cloned version:</B>
<div class="juris_name">
</div>

jQuery:

$('.selectpicker').selectpicker("toggle");

$(document).on("click", "#clonejurisdiction", function() {
  addselectpicker();
});

function addselectpicker() {
  var clone = $('#jurisdictionpicker').clone();
  clone.find(".selectpicker").attr("id",'jurisdictionpicker2');
  clone.find("[data-id='jurisdiction_']").remove();
  clone.appendTo(".juris_name");
  clone.find('.selectpicker').selectpicker("toggle");
}

1 个答案:

答案 0 :(得分:1)

如果将内容包装在超时中,则似乎可以正常工作。也许插件需要时间来完成它的工作。

$('.selectpicker').selectpicker("toggle");
var index = 1;

$(document).on("click", "#clonejurisdiction", function() {
  addselectpicker();
});

function addselectpicker() {
  var clone = $('#jurisdictionpicker').clone();
  clone.attr('id', 'jurisdictionpicker' + index);
  clone.find(".selectpicker").attr("id", 'jurisdictionpicker' + index);
  index++;
  clone.find("[data-id='jurisdiction_']").remove();
  clone.appendTo(".juris_name");

  setTimeout(function() {
    clone.find('.selectpicker').selectpicker("toggle");
  }, 0);
}

Demo