Twitter Bootstrap - selectpicker 在通过 JS 添加它们后没有反应

Twitter Bootstrap - selectpicker isn't reacting after adding them by JS

我对 bootstrap 附加组件 select picker. I'm dynamicly adding them by JS, and they won't to be active after adding. They're just there, you can click on them, but you can't select the option. Here is simplified code (or here is LIVE DEMO) 有疑问。

<script>
$(function () {
    $("#add").click(function () {
        $(".pattern").clone().removeClass("hidden pattern").addClass("col-md-24 added").prependTo("#next-line");
    });

    $(".remove").click(function () {
        console.log("remove");
        $(this).parent('.added').remove();
    });
    $('.selectpicker').selectpicker();

    });
</script>
<!-- .... -->
<button type="button" id="add" class="btn btn-success"><span class="fa fa-plus"></span></button>
<form method="POST"> 
        <select class="selectpicker" name="id[]" data-live-search="true">
            <!-- .... -->
        </select>

    <div id="next-line">
    </div>
    <button type="submit" name="save" class="btn btn-lg btn-success"><span class="fa fa-lg fa-send"></span> Send</button>
</form>

<div class="pattern hidden">
    <select class="selectpicker"  name="id[]"  data-live-search="true">
        <!-- .... -->
    </select>
</div>

感谢您的帮助。

您正在克隆一个已经是 selectpicker 实例的元素。

由于你隐藏的 select 只是一个要克隆的模式,我建议你从中删除 selectpicker class。

然后,你就可以克隆了。
但在添加之前,给它一个唯一的 ID,这将有助于在其上启动 selectpicker。

$("#add").click(function() {
    var myClone = $(".pattern").clone().removeClass("hidden pattern").addClass("col-md-24 added");
    var nb = $(".added").length+1;

    myClone.attr("id", "added_"+nb).prependTo("#next-line");
    $("#next-line").find('#added_'+nb).find("select").selectpicker(); //load again
});

这样,您肯定会仅在新添加的元素上启动 select选择器。
;)

正在CodePen