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

动态添加含Select2的DOM行后组件失效,如何让每行Select2正常工作?

解决新增表格行后Select2组件无法正常运行的问题

问题根源

  • Select2仅在页面加载时初始化已存在的DOM元素,动态添加的新元素需要手动重新初始化
  • 原代码克隆带固定ID的元素,导致DOM中出现多个重复ID,违反HTML规范,同时干扰Select2的正常工作

解决步骤

  1. 替换重复ID为类名:把模板行的id="mainsection"改成class="mainsection",下拉框移除固定IDid="dd_artikli",只保留类名select2-multiple,避免ID冲突
  2. 克隆后初始化新行的Select2:新行添加到DOM后,找到其中的下拉框,调用.select2()完成初始化
  3. 修复行号计数:给每一行生成独立行号,而非仅修改第一行的计数

修正后的完整代码

<table id="add_new" style="width: 100%; margin-top:40px;" class="col-12 col-lg-12 col-md-12 col-sm-12 col-xl-12">
    <thead>
        <tr>
            <th style="text-align:left; font-size: 10px; color:#8f8f8f; padding-bottom: 15px; width: 10%;">
                Zap. št.:
            </th>
            <th style="text-align:left; font-size: 10px; color:#8f8f8f; padding-bottom: 15px; width: 50%;">
                Naziv artikla
            </th>
            <th style="text-align:left; font-size: 10px; color:#8f8f8f; padding-bottom: 15px; width: 20%;">
                Količina
            </th>
            <th style="text-align:right; font-size: 10px; color:#8f8f8f; padding-bottom: 15px; width: 20%;">
                EM (kos/m/colli,...)
            </th>
        </tr>
    </thead>
    <tbody>
        <!-- 模板行改用类名标识,移除重复ID -->
        <tr class="mainsection">
            <td>
                <p class="row-count" style="font-size: 13px; text-decoration: none; line-height: 1; color:#909090; margin-top:0px; margin-bottom:0;">
                    1
                </p>
            </td>
            <td style="padding-top:0px; padding-bottom:5px;">
                <h4 style="font-size: 16px; line-height: 1; margin-bottom:0; color:#303030; font-weight:500; margin-top: 10px;">
                    <!-- 移除固定ID,保留类名 -->
                    <select class="form-control select2-multiple" data-width="100%">
                        <option value="">Select country</option>
                        <?php
                        if (count($itemRecords_artikli) > 0) {
                            foreach ($itemRecords_artikli as $ct) {
                        ?>
                                <option value="<?php echo $ct['id']; ?>">
                                    <?php echo $ct['name']; ?>
                                </option>
                        <?php
                            }
                        }
                        ?>
                    </select>
                </h4>
            </td>
            <td contenteditable>
                <p style="font-size: 13px; text-decoration: none; line-height: 1; color:#909090; margin-top:0px; margin-bottom:0;">
                </p>
            </td>
            <td contenteditable style="padding-top:0px; padding-bottom:0; text-align: right;">
                <p style="font-size: 13px; line-height: 1; color:#303030; margin-bottom:0; margin-top:0; vertical-align:top; white-space:nowrap;">
                </p>
            </td>
        </tr>
    </tbody>
</table>

<script>
    // 初始化页面加载时已存在的Select2组件
    $(document).ready(function() {
        $('.select2-multiple').select2();
    });

    var number = 1;
    document.getElementById("newsectionbtn").onclick = function() {
        var container = document.getElementById("add_new").querySelector('tbody');
        // 获取模板行(第一个带mainsection类的行)
        var section = document.querySelector('.mainsection');
        number++;

        // 克隆模板行,true表示克隆所有子元素及事件
        var newRow = section.cloneNode(true);
        // 更新新行的行号
        newRow.querySelector('.row-count').textContent = number.toString();
        // 重置新行下拉框的选中值
        var selectElement = newRow.querySelector('.select2-multiple');
        selectElement.value = "";

        // 将新行添加到表格tbody中
        container.appendChild(newRow);

        // 初始化新行中的Select2组件
        $(selectElement).select2();
    }
</script>

<?php
/*
 @Author: Sanjay Kumar
 @Project: PHP MySQLi How To Use Select2 for Multiple Select Tutorial
 @Email: onlinewebtutorhub@gmail.com
 @Website: https://onlinewebtutorblog.com/
*/

// Include the database configuration file
require 'dbconfig.php';

$countrySelect = $conn->prepare("SELECT * FROM artikli");

$countrySelect->execute();
$countries = $countrySelect->get_result();

$itemRecords_artikli = array();
while ($item = $countries->fetch_assoc()) {
    extract($item);
    $itemDetails = array(
        "id" => $id,
        "name" => $naziv
    );
    array_push($itemRecords_artikli, $itemDetails);
}
?>

注意事项

  • 确保页面已正确引入jQuery和Select2的CSS、JS文件,这是Select2正常运行的基础
  • 永远不要在DOM中出现重复ID,用类名来标记需要重复使用的元素
  • 动态添加的Select2元素必须手动调用初始化方法,否则无法渲染出Select2的样式和功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:48:25