本文讲解如何避免为每个带数字后缀的 css 类(如 details-control-1)重复注册事件监听器,转而采用语义化、可维护的委托式事件绑定方案。
在实际 Web 开发中,常见一种“动态生成带序号类名”的做法——例如 PHP 循环输出
、
等。这种写法看似直观,却会引发两个关键问题:
选择器不可扩展
:jQuery 无法通过 tr.details-control- 在循环中动态拼接并正确绑定事件(因脚本执行时 $i 已超出作用域,且大量内联
.details-control {
cursor: pointer;
}
.details-control.active {
background-color: #ffeb3b;
}
$(function() {
const $table = $("#table-overview");
// 使用事件委托:监听 tbody 下所有 .details-control 的 click 事件
$table.on("click", "tr.details-control", function() {
// 移除其他行的 active 状态
$table.find("tr.details-control").removeClass("active");
// 为当前点击行添加 active 状态
$(this).addClass("active");
// 可选:读取数据索引,用于后续业务逻辑
const index = $(this).data("index");
console.log("Clicked row index:", index); // 输出 0, 1, 2...
});
});
⚠️ 关键注意事项
不要在 PHP 循环中嵌入