jQuery select2 append in table TR 后没有出现

jQuery Select2 does not appear after append in table TR

我正在尝试在 table 的列中附加一个 Select2 输入框。它在第一行工作正常,因为它在 HTML 中是静态的。然后当我点击一个按钮追加另一行时,select2 不会出现。

html中的代码和table部分的js应该是相同的,但我不知道可能是什么原因。

这是屏幕截图,请忽略 UI 不一致之处,我在该页面中还有更多问题,但那是另一回事。

这里是fiddle,https://jsfiddle.net/unmuk4km/2/

HTML

                                <table class="table table-hover" id="tab_owner">
                                    <thead>
                                        <tr>
                                            <th class="text-center" colspan="4"><a
                                                class="btn green add-owner pull-left"><i
                                                class="fa fa-plus"></i>Add New Owner</a></th>
                                        </tr>
                                        <tr>
                                                <th> Matrik No. </th>
                                                <th> IC No.</th>
                                                <th> Birth Place</th>
                                                <th> Faculty</th>
                                                <th> Study Year</th>
                                                <th> Phone No.</th>
                                                <th> Email</th>
                                                <th> Year Start Business</th>
                                                <th width="3%"></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr id="owner_0">
                                            <td width='15%'><input name="matrik_number" type="text" class="form-control select2"></td>
                                            <td width='10%'><input name="ic_0" type="text" class="form-control" readonly></td>
                                            <td width='8%'><input name="bp_0" type="text" class="form-control" readonly></td>
                                            <td width='5%'><input name="fac_0" type="text" class="form-control" readonly></td>
                                            <td width='5%'><input name="syear_0" type="text" class="form-control" readonly></td>
                                            <td width='8%'><input name="student_phoneno_0" type="text" class="form-control"></td>
                                            <td width='10%'><input name="student_emailadd_0" type="text" class="form-control"></td>
                                            <td width='3%'><select name="business_yearstart_0" class="form-control required">
                                                <option value=""></option>
                                                <option value="1">1</option>
                                                <option value="2">2</option>
                                                <option value="3">3</option>
                                                <option value="4">4</option>
                                                </select>
                                            </td>

                                            <td width='3%'><!-- placeholder for remove button --></td>   
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>

JS

tab_owner.on('click', '.add-owner', function (e){
            e.preventDefault();

            var iRow = $('tbody tr:last',tab_owner).index() + 1;
            var show_studentdata = $("<tr id='owner_"+ iRow +"' >\n" +
                        "<td width='15%'><input name='matrik_number_"+ iRow +"' type='text' class='form-control'></td>\n" +
                        "<td width='10%'><input name='ic_"+ iRow +"' class='form-control' readonly></td>\n" +
                        "<td width='8%'><input name='bp_"+ iRow +"' class='form-control' readonly></td>\n" +
                        "<td width='5%'><input name='fac_"+ iRow +"' class='form-control' readonly></td>\n" +
                        "<td width='5%'><input name='syear_"+ iRow +"' class='form-control' readonly></td>\n" +
                        "<td width='8%'><input name='student_phoneno_"+ iRow +"' class='form-control'></td>\n" +
                        "<td width='10%'><input name='student_emailadd_"+ iRow +"' class='form-control'></td>\n" +
                        "<td width='3%'><select name='business_yearstart_"+ iRow +"'></select></td>\n" +
                        "<td width='3%'><a class='btn btn-outline btn-circle btn-sm red del-owner pull-right'><i class='fa fa-remove'></i>Remove</a></td>" +
                        "</tr>\n");



            //insert modal data to tables/forms
            $('tbody',tab_owner).append(show_studentdata);

            Metronic.scrollTo(show_studentdata, slideOffeset);

        });

        function loadStudentDetails(d){
            $('[name^=ic_'+ iRow +']').val(d.smIcNo);
            $('[name^=bp_'+ iRow +']').val(d.smBirthPlace);
            $('[name^=fac_'+ iRow +']').val(d.smFacultyCode);
            $('[name^=syear_'+ iRow +']').val(d.studyyear);
            student_phoneno.val(d.smHandphoneNo);
            student_emailadd.val(d.smEmailAddr);
            }

        matrik_number
        .select2({
            allowClear: true,
            placeholder: "Filter as you type",
            minimumInputLength: 3,
            ajax: {
                url: 'home/umkei/info/student',
                dataType: 'json',
                quietMillis: 250,
                data: function (term, page) {
                    return { q: term };
                },
                results: function (data, page) {
                    return { results: data };
                },
                cache: true
            }
        })
        .on("change", function(e) {
            var id = matrik_number.val();

            if(id != ''){
                $.ajax({
                    url: 'home/umkei/info/student/'+id,
                    dataType: 'json',
                    beforeSend:function(){
                        showMetronicLoading(el,msgLoading);
                    },
                    error: function(){
                        Metronic.unblockUI(el);


showMetronicAlert('danger','warning',msgInternetError + '. Failed to load Student Info.');
                    },
                    success: function(res){
                        Metronic.unblockUI(el);

                        loadStudentDetails(res);

                    }
                });
            }
        });

fiddle 无法正常工作,因为我以前从未使用过它,但我在日志中发现了一些错误,但我不知道出了什么问题,所以我对此深表歉意。

但是您应该对我的代码的外观有所了解。我一直在这里和那里更改和测试东西,如果某些代码看起来不一致,请原谅我,因为我一定是在将它放入 fiddle.

时错过了它

谢谢。

您需要在附加后初始化新的 select2。

将您的 select2 初始化代码包装在一个函数中并调用它,使用 starts with name.

tab_owner.on('click', '.add-owner', function(e) {
  e.preventDefault();

  var iRow = $('tbody tr:last', tab_owner).index() + 1;
  var show_studentdata = $("<tr id='owner_" + iRow + "' >\n" +
    "<td width='15%'><input name='matrik_number_" + iRow + "' type='text' class='form-control'></td>\n" +
    "<td width='10%'><input name='ic_" + iRow + "' class='form-control' readonly></td>\n" +
    "<td width='8%'><input name='bp_" + iRow + "' class='form-control' readonly></td>\n" +
    "<td width='5%'><input name='fac_" + iRow + "' class='form-control' readonly></td>\n" +
    "<td width='5%'><input name='syear_" + iRow + "' class='form-control' readonly></td>\n" +
    "<td width='8%'><input name='student_phoneno_" + iRow + "' class='form-control'></td>\n" +
    "<td width='10%'><input name='student_emailadd_" + iRow + "' class='form-control'></td>\n" +
    "<td width='3%'><select name='business_yearstart_" + iRow + "'></select></td>\n" +
    "<td width='3%'><a class='btn btn-outline btn-circle btn-sm red del-owner pull-right'><i class='fa fa-remove'></i>Remove</a></td>" +
    "</tr>\n");

  //insert modal data to tables/forms
  $('tbody', tab_owner).append(show_studentdata);

  renderSelect2(); // call to render select2

  Metronic.scrollTo(show_studentdata, slideOffeset);

});

function loadStudentDetails(d) {
  $('[name^=ic_' + iRow + ']').val(d.smIcNo);
  $('[name^=bp_' + iRow + ']').val(d.smBirthPlace);
  $('[name^=fac_' + iRow + ']').val(d.smFacultyCode);
  $('[name^=syear_' + iRow + ']').val(d.studyyear);
  student_phoneno.val(d.smHandphoneNo);
  student_emailadd.val(d.smEmailAddr);
}

function renderSelect2() {

  $('[name^="matrik_number"]')
    .select2({
      allowClear: true,
      placeholder: "Filter as you type",
      minimumInputLength: 3,
      ajax: {
        url: 'home/umkei/info/student',
        dataType: 'json',
        quietMillis: 250,
        data: function(term, page) {
          return {
            q: term
          };
        },
        results: function(data, page) {
          return {
            results: data
          };
        },
        cache: true
      }
    })
    .on("change", function(e) {
      var id = matrik_number.val();

      if (id != '') {
        $.ajax({
          url: 'home/umkei/info/student/' + id,
          dataType: 'json',
          beforeSend: function() {
            showMetronicLoading(el, msgLoading);
          },
          error: function() {
            Metronic.unblockUI(el);


            showMetronicAlert('danger', 'warning', msgInternetError + '. Failed to load Student Info.');
          },
          success: function(res) {
            Metronic.unblockUI(el);

            loadStudentDetails(res);

          }
        });
      }
    });
}

renderSelect2();

FIDDLE