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

时间:2017-04-01 12:19:52

标签: javascript jquery html asp.net select2

我尝试了很多资源:

Cloned Select2 is not responding

select2 is not working

select2 is not working

Initialising select2 created dynamically

How to execute select2() function on dynamically created select list?

Select2 not displayed when added dynamically for the first time

说明:

  

使用Razor构建查看页面。我正在尝试使用JQuery克隆row,第一个正常工作,新创建(动态)未打开(冻结)。   图片:   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'.

帮帮我。

1 个答案:

答案 0 :(得分:0)

在将新选择添加到页面后,您似乎没有初始化新选择。

您需要在页面上添加新脚本(并运行它),设置选择,否则他们只会坐在那里。

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

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

如果你要克隆多个select,那么我猜你可以只添加一次init脚本,因为它应该初始化每个克隆选择。