克隆的 Select2 在 Asp.Net 中不起作用

Cloned Select2 is not working in Asp.Net

我尝试了很多资源:

Cloned Select2 is not responding

解释:

View page is build up using Razor. i'm trying to clone the row using JQuery, first one is working properly and newly created( dynamic) is not opening (freezed). Image: image link

查看代码:

                        <div id="ROW_0" class="template">
                            <hr />
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Credit Account</label>
                                        @Html.DropDownListFor(model => model.AccountsId, new SelectList(Model.Accountss, "Id", "Name"), "-- select account --", new { @class = "form-control select required select2insidemodal", @id = "creditAccount" })
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Amount</label>
                                        @Html.EditorFor(model => model.Credit, new { htmlAttributes = new { @class = "form-control", @type = "text", @id = "credit" } })
                                    </div>
                                    <span id="error-@Html.NameFor(vm => vm.Credit)" class="dN cR"></span>

                                </div>
                            </div>
                        </div>

脚本:

//button for adding row 
$(document).ready(function () {

  $(document).on('click', "#addMore",function (e) {
             addNewRow();
         });
         
        function addNewRow() {
            var div = $(".template").clone().html();

            //find all select2 and destroy them   
           $(div).find(".select2").each(function (index) {
                if ($(this).data('select2')) {
                    $(this).select2('destroy');
                }
            });


           $("#dynamicBlock").prepend(div); //adding cloned data to new div '#dynamicBlock'.

帮帮我。

您似乎没有在将新 select 附加到页面后对其进行初始化。

您需要将新脚本附加到页面(和 运行 它),以设置 select,否则它们将停滞不前。

var initScript = '$(".select2insidemodal").select2();';

$('<script>' + initScript + '</' + 'script>').appendTo(document.body);

如果您要克隆多个 select,那么我想您可以只在最后一次添加初始化脚本,因为它应该初始化每个克隆的 select.