Select2 JQuery不会通过按钮添加新选择器来更新Dom

时间:2018-08-12 21:24:11

标签: javascript jquery html bootstrap-4

我正在使用选择器2(https://select2.org),我有一个选择器来选择食物。我希望添加一个带有底部的新选择器。我已经做到了,但是当Dom刷新时,它显示出一个错误的选择器: up good selector and in down the new selector (the bad selector)

<div class="container">
    <div class="row">
        <!-- style="padding-top: 1rem; padding-left: 2rem" -->
        <div class="col-sm-12">
            <b>Food:</b>
            <select id="selectpicker1" data-live-search="true" data-width="70%">
                <option data-tokens="Hotdog" value="Hotdog">Hot Dog</option>
                <option data-tokens="Burger" value="Burger">Burger</option>
                <option data-tokens="Sugar" value="Sugar">Sugar</option>
                <option data-tokens="Donut" value="Sugar">Donut</option>
            </select>
            <button id="b1" class="add-more btn-success" type="button" onclick="doFunction()" ;>+</button>
        </div>
    </div>
    <div id="ss"></div>
    <script>
        function doFunction() {
            $(ss).append
            (
                '<div class="row">' +
                '<div class="col-sm-12">' +
                '<b>Food:</b>' +
                '<select  id="selectpicker1" data-live-search="true" data-width="70%">' +
                '<option data-tokens="Hotdog" value="Hotdog">Hot Dog<option>' +
                '<option data-tokens="Burger" value="Burger">Burger</option>' +
                '<option data-tokens="Sugar" value="Sugar">Sugar</option>' +
                '<option data-tokens="Donut" value="Sugar">Donut</option>' +
                '</select>' +
                '<button id="b1" class="add-more btn-success" type="button" onclick="doFunction()";>+</button>' +
                '</div>' +
                '</div>'
            );
        }
    </script>
</div>

您有一些解决办法吗?

1 个答案:

答案 0 :(得分:0)

您只需要在逻辑之后重新调用select2函数:

   <script>
    function doFunction() {
        $(ss).append
        (
            '<div class="row">' +
            '<div class="col-sm-12">' +
            '<b>Food:</b>' +
            '<select  id="selectpicker1" data-live-search="true" data-width="70%">' +
            '<option data-tokens="Hotdog" value="Hotdog">Hot Dog<option>' +
            '<option data-tokens="Burger" value="Burger">Burger</option>' +
            '<option data-tokens="Sugar" value="Sugar">Sugar</option>' +
            '<option data-tokens="Donut" value="Sugar">Donut</option>' +
            '</select>' +
            '<button id="b1" class="add-more btn-success" type="button" onclick="doFunction()";>+</button>' +
            '</div>' +
            '</div>'
        );
      // Here you can add the initialize
      // Important be sure you insert the library select 2 
      // If is not the case you will get an error undefined select2() 
      $('select').select2();

    }
</script>

请注意,如果您未将select2应用于所有选择,则不能将选择更改为任何其他选择器。