动态生成输入行的Autocomplete功能失效问题求助
解决动态生成行中Autocomplete失效的问题
问题根源
- ID重复冲突:模板行里的input使用固定ID(
tutorial_name),动态生成多行后会出现多个相同ID的元素,违反HTML规范,导致jQuery无法正确识别新元素。 - 未给动态元素初始化插件:初始代码仅对页面加载时存在的元素绑定Autocomplete,动态生成的新元素未触发插件初始化流程。
修复步骤
1. 调整HTML模板,用类选择器替代固定ID
移除模板行input的固定ID,保留用于识别的类名:
<form method="POST"> <table class="table table-bordered"> <thead class="table-success" style="background-color: #3fbbc0;"> <tr> <th width="15%"><center>Service</th> <th width="10%"><center>Mach No</th> <th width="10%"><center>Consultant</th> <th width="5%"><center>Qty</th> <th> <button type="button" class="btn btn-sm btn-success" onclick="BtnAdd()">+</button> </th> </tr> </thead> <tbody id="TBody"> <tr id="TRow" class="d-none"> <!-- 移除固定ID,保留scode类 --> <td><input type="text" class="scode form-control text-end" name="scode[]" onchange="GetDetail(this.closest('tr'))"></td> <td><input type="text" class="qty form-control text-end" name="qty[]" onfocus="Calc(this);"></td> <td><button type="button" class="btn btn-sm btn-danger" onclick="BtnDel(this)">-</button></td> </tr> </tbody> </table> </form> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script type="text/javascript" src="frontend-script.js"></script>
2. 修改JS逻辑,支持动态元素初始化
封装Autocomplete初始化函数,在动态添加行时为新元素绑定插件:
// 封装通用的Autocomplete初始化方法 function initAutocomplete(element) { $(element).autocomplete({ source: 'backend-script.php' }); } // 页面加载时初始化已存在的scode元素 $(function() { initAutocomplete(".scode"); }); // 调整添加行函数 function BtnAdd() { var newRow = $("#TRow").clone().appendTo("#TBody"); $(newRow).find("input").val(''); $(newRow).removeClass("d-none"); // 给新行的scode输入框初始化Autocomplete initAutocomplete($(newRow).find(".scode")); // 更新行序号 $(newRow).find("th").first().html($('#TBody tr:not(.d-none)').length); } function BtnDel(v) { $(v).parent().parent().remove(); GetTotal(); // 重新更新剩余行的序号 $("#TBody tr:not(.d-none)").each(function(index){ $(this).find("th").first().html(index + 1); }); }
3. 修复后端SQL注入风险
原代码直接拼接用户输入到SQL语句中,存在安全隐患,改用预处理语句:
<?php include('database.php'); $searchTerm = $_GET['term'] ?? ''; // 使用预处理语句避免注入 $sql = "SELECT * FROM machine1 WHERE user_id LIKE ?"; $stmt = $conn->prepare($sql); $likeTerm = "%{$searchTerm}%"; $stmt->bind_param("s", $likeTerm); $stmt->execute(); $result = $stmt->get_result(); $tutorialData = array(); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { $data['id'] = $row['id']; $data['value'] = $row['user_id']; array_push($tutorialData, $data); } } echo json_encode($tutorialData); // 关闭连接和语句 $stmt->close(); $conn->close(); ?>
核心说明
- 类选择器替代ID:避免动态生成元素的ID冲突,确保插件能正确选中目标元素。
- 动态绑定插件:动态添加的DOM元素需要在生成后重新初始化插件,因为页面加载时的初始化仅作用于当时存在的元素。
- SQL安全:预处理语句是防范SQL注入的标准方案,禁止直接拼接用户输入到SQL语句中。
内容的提问来源于stack exchange,提问作者Moon
相关产品推荐
相关产品推荐

