本文介绍如何优化含 50+ 动态行的采购/发票表格,避免为每行绑定独立 ajax 请求,改用事件委托 + 统一函数 + `data-id` 标识实现「一次配置、全局响应」,显著提升性能与可维护性。
在构建多行商品录入表(如进销存系统中的发票单据)时,常见做法是为每个输入框(如 #productCode_1、#productCode_2 … #productCode_50)单独绑定 change 事件并调用独立的 AJAX 函数(如 getDataFromServer1()、getDataFromServer2())。这种方式看似直观,但存在严重问题:代码冗余高、难以维护、性能差(50 个监听器 + 50 次潜在请求)、且无法动态扩展行数。
✅ 正确解法是采用 事件委托(Event Delegation) + 语义化类名 + 行标识符(data-id),将全部逻辑收敛至一个通用函数中。
统一添加语义化 class 并注入行索引
为所有商品编码输入框添加公共类 product-code,并通过 data-id="" 显式标记当前行为第几行:
同样地,为关联字段(如 productName_1、price_2 等)添加对应类(如 product-name、price)并保留 data-id,便于后续精准定位。
使用 jQuery(document).on() 绑定动态事件
利用事件冒泡机制,在 document(或更优的父容器)上监听 .product-code 的 change 事件——该方式天然支持未来动态插入的新行:
jQuery(document).on('change', '.product-code', function() {
var PID = jQuery(this).val();
var itemId = jQuery(this).attr('data-id');
var nextItemId = parseInt(itemId) + 1;
getDataFromServer(PID, itemId);
jQuery("#productCode_" + nextItemId).focus(); // 自动聚焦下一行
});编写通用 AJAX 处理函数
getDataFromServer(PID, itemId) 接收商品 ID 和行号,动态拼接选择器更新对应行字段:
function getDataFromServer(PID, itemId) {
$.ajax({
type: "POST",
url: "response.php",
data: { pro_id: PID },
dataType: "json", // ✅ 更安全:自动解析 JSON,无需手动 JSON.parse()
success: function(response) {
// ✅ 使用 itemId 动态定位目标元素
$('#productName_' + itemId).val(response.pro_name);
$('#productOnHand_' + itemId).val(response.pro_quantity);
$('#price_' + itemId).val(response.pro_price);
$('#quantity_' +
itemId).val(1);
// 可选:触发计算总金额(如 quantity * price)
calculateRowTotal(itemId);
},
error: function(xhr, status, error) {
console.error("AJAX 请求失败(行 " + itemId + "):", error);
alert("商品信息加载失败,请检查编号是否正确");
}
});
}
// 示例:计算单行小计(quantity × price)
function calculateRowTotal(itemId) {
const qty = parseFloat($('#quantity_' + itemId).val()) || 0;
const price = parseFloat($('#price_' + itemId).val()) || 0;
$('#total_' + itemId).val((qty * price).toFixed(2));
}通过以上重构,代码行数减少 80%+,维护成本大幅降低,且为后续增加校验、自动补全、批量操作等功能预留了清晰架构。真正的工程效率,始于一次优雅的抽象。