You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript动态添加Select2类失效及样式异常问题求助

动态添加Select2下拉框样式异常修复方案

问题现象

  • 动态新增表格行中的<select>元素无法渲染Select2样式,显示为原生下拉框
  • 首次添加的下拉框宽度为默认值,后续新增的下拉框宽度出现异常变化

问题根源

  1. 初始化对象错误:原代码中错误地给<option>标签调用select2()方法,而Select2需要绑定在<select>元素上
  2. 初始化时机不对:在元素插入DOM之前就尝试初始化Select2,导致样式无法正确挂载
  3. 宽度未统一配置:未指定Select2的宽度,导致动态添加时元素宽度自适应出现偏差

修复步骤

  1. 修正初始化对象:找到新行中的<select>元素,在该元素上调用select2(),而非<option>
  2. 调整初始化时机:将Select2初始化代码放在新行插入DOM之后执行
  3. 统一宽度配置:初始化Select2时指定width: '100%',使其继承父容器的宽度,保持样式一致

修复后的完整代码

HTML部分

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.6.4.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<div class="table-responsive text-nowrap">
  <table class="table table-striped" id="submissionTable">
    <thead>
      <tr>
        <th>#</th>
        <th>ITEM</th>
        <th>QTY</th>
        <th>MEASURE BY</th>
        <th>UNIT PRICE</th>
        <th>LINE TOTAL</th>
      </tr>
    </thead>
    <tbody class="table-border-bottom-0">
      <tr id="tablerow0"></tr>
    </tbody>
  </table>
  <p>
    <button id="add" type="button" class="btn btn-primary">Add</button>
  </p>
</div>

JavaScript部分

var counter = 1;
var dropdownOptions = @Html.Raw(Json.Encode(ViewBag.Item_ID));

$(function () {
  $("#add").click(function () {
    var newRow = $(
      '<tr id="tablerow' +
      counter +
      '" class ="poSet"> ' +
      "<td>" +
      '<label id="CountItems"><strong>' +
      counter +
      "</strong></label>" +
      "</td>" +
      '<td width="40%">' +
      '<select onchange="sendInfo(this)" class="form-select ItemId" data-id= ' + counter + ' name="Item_Id[' +
      counter +
      ']" id="ItemId[' + counter + ']" required="required" ' +
      "</select>" +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control Qty" name="Qty[' +
      counter +
      ']" value="1" id="Qty[' + counter + ']" onchange="calQtyBase(this)" data-QtyId= ' + counter + ' required="required" />' +
      "</td>" +
      '<td width="10%">' +
      '<input type="text" class="form-control" name="MeasureBy[' +
      counter +
      ']" value="" id="MeasureBy[' + counter + ']" readonly />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control UnitPrice" name="Unit_Price[' +
      counter +
      ']" value="0.00" id="UnitPrice[' + counter + ']"  onchange="priceBase(this)" data-PriceId= ' + counter + '  required="required" />' +
      "</td>" +
      '<td width="20%">' +
      '<input type="text" class="form-control LineTotal" name="Line_Total[' +
      counter +
      ']" value="0.00" id="LineTotal[' + counter + ']"    required="required" />' +
      "</td>" +
      "<td>" +
      '<button type="button" class="btn btn-danger" onclick="removeTr(' +
      counter +
      ');">x</button>' +
      "</td>" +
      "</tr>"
    );

    var selectElement = newRow.find("select");
    // 填充下拉选项
    dropdownOptions.forEach(function (option) {
      var optionElement = $("<option>").val(option.Value).text(option.Text);
      selectElement.append(optionElement);
    });

    // 将新行插入DOM后再初始化Select2
    newRow.appendTo("#submissionTable");
    // 初始化Select2并设置宽度
    selectElement.select2({
      width: '100%'
    });

    counter++;
    return false;
  });
});

内容的提问来源于stack exchange,提问作者Dev Beginner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 17:10:01