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

jQuery遍历元素添加上标异常:如何为对应.footer添加序号上标

问题分析

你的代码核心问题是:在遍历span.footnote的循环中,每次执行$('<sup>' + (index + 1) + '</sup>').insertAfter('.footer')时,会选中页面上所有的.footer元素,导致每一次循环都给所有.footer追加序号。第一次循环(index=0)给两个.footer都加1,第二次循环(index=1)又给两个.footer都加2,最终每个.footer后面都会出现重复的序号。

修正代码

解决思路是先获取所有.footer元素的集合,然后在遍历footnote时,通过索引匹配对应的.footer元素,只给当前索引的元素追加序号:

$(document).ready(function () {
  var $notes = $('<ol id="notes"></ol>').insertAfter('#hexagon');
  // 先获取所有.footer元素的集合
  var $footers = $('.footer');

  $('span.footnote').each(function (index) {
    // 通过eq(index)定位当前索引对应的.footer元素
    $('<sup>' + (index + 1) + '</sup>').insertAfter($footers.eq(index));
    $(this).appendTo($notes).wrap('<li></li>');
  });
});
效果说明
  • 遍历span.footnote时,index从0开始递增,index+1就是对应的脚注序号
  • $footers.eq(index)会精准选中第index个.footer元素,只在它后面插入对应序号的上标
  • 同时将当前footnote元素移动到有序列表中并包裹为<li>,完成脚注内容的迁移

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:30:44