本文详解如何正确使用 jQuery 的 .each() 遍历并为多个 .numeration 元素依次分配字母表中的对应字符,避免所有元素被统一赋值为最后一个字母的常见错误。
本文详解如何正确使用 jquery 的 `.each()` 遍历并为多个 `.numeration` 元素依次分配字母表中的对应字符,避免所有元素被统一赋值为最后一个字母的常见错误。
在前端开发中,常需为一组动态生成的 DOM 元素(如
✅ 正确实现方式
核心在于:利用 .each() 回调函数的 index 参数直接映射数组下标,避免额外 for 循环,并始终操作当前遍历节点($(this)),而非全局选择器:
const alphabetArray = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U"
];
$(".numeration").each(function(index) {
// ✅ $(this) 指向当前遍历的单个 .numeration 元素
// ✅ index 自动递增:0→A, 1→B, ..., 20→U
$(this).html(alphabetArray[index]);
});
❌ 原代码问题解析
- 作用域错误:$(".numeration").html(...) 每次都重置所有匹配元素的内容,导致前 20 次赋值被覆盖,最终全部显示 "U";
- 逻辑冗余:内部 for 循环使每个 .numeration 元素被重复赋值 21 次(i
⚠️ 注意事项与健壮性建议
-
长度校验:若 .numeration 元素数量超出 alphabetArray 长度(21 个),alphabetArray[index] 将返回 undefined。建议增加防护:
$(this).html(alphabetArray[index] ?? `#${index + 1}`); -
性能考量:现代项目推荐优先使用原生 JavaScript 替代 jQuery:
document.querySelectorAll('.numeration').forEach((el, i) => { el.textContent = alphabetArray[i] ?? ''; }); - 可扩展性:如需支持更多字母或自定义序列,可将 alphabetArray 抽离为配置项,或动态生成(如 Array.from({length:21}, (_,i) => String.fromCharCode(65+i)))。
通过精准绑定索引与元素实例,即可优雅实现字母序号化渲染——简洁、高效、无副作用。










