【问题标题】:Dynamically add Select2 to Row将 Select2 动态添加到 Row
【发布时间】:2018-10-23 18:50:15
【问题描述】:

为什么当我尝试将 select2 添加到新行时,新的 select2 无法初始化(它显示为 select html 标记)。

这是我创建表格的代码:

<table id="tbldet" class="table table-bordered table-striped table-hover" style="width:100%;margin:0 auto;">
  <thead>
    <tr>
      <th><p>Nama Barang</p></th>
      <th><p>Harga</p></th>
      <th><p>Qty</p></th>
      <th><p>Total</p></th>
      <th style="width:50px"><p>Aksi</p></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
          <select class="select2" name="det_brg" style="width:100%;">
          </select>
      </td>
      <td>10000</td>
      <td>4</td>
      <td>930000</td>
      <td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>
    </tr>
  </tbody>
</table>

初始化选择的javascript函数:

function initializeSelect2(selectElementObj) {
  selectElementObj.select2({
    width: "80%",
    tags: true,
    language:"id",
    ajax: {
        url: "controller/barang_list.php",
        dataType: "json",
        type:"GET",
        delay: 250,
        data: function (params) {
            return {
                search: params.term
            }
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                  return {
                    id:item.id,
                    text:item.text
                  }
                })
            };
        },
        cache: false
    },
    minimumInputLength: 3,
    dropdownParent:$("#form-data")
  });
};
    $(".select2").each(function() {
      initializeSelect2($(this));
    });

这是添加新行的代码:

//create new row
$("#add_row").click(function(e) {
  //new row
  $("#tbldet").append(
    '<tr>\
        <td>\
            <select class="select2" name="det_brg" style="width:100%;">\
            </select>\
        </td>\
        <td>10000</td>\
        <td>4</td>\
        <td>930000</td>\
        <td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>\
    </tr>'
  );
  var newSelect=$(this).closest("tr").find(".select2");
  initializeSelect2(newSelect);
})

我怀疑在新行上查找新的“select2”组件存在问题,但是当我使用 alert(newSelect) 时,它没有显示 NULL / Undefined

【问题讨论】:

  • 一个jQuery选择器永远不会为空或未定义,如果它没有找到一个元素,它会返回一个长度为0的jQuery对象。当console.log(newSelect)时它会显示什么?

标签: javascript jquery jquery-select2


【解决方案1】:

您的怀疑是正确的,您的代码将永远找不到新的.select2 元素。原因与.closest() 的工作方式有关。您可以在这里进行调查:

https://api.jquery.com/closest/

但与此同时:

改变

var newSelect=$(this).closest("tr").find(".select2");

var newSelect=$("#tbldet").find(".select2").last();

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2018-06-12
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    相关资源
    最近更新 更多