如何用jQuery/原生JS拼接锚标签ID到新href并替换页面href属性
没问题!这里有两种实用方案帮你完成需求,不管用原生JavaScript还是jQuery都能轻松处理动态且非唯一id的情况:
原生JavaScript方案
直接用原生API就能实现,核心是选中所有带id属性的<a>标签,然后逐个修改它们的href属性:
// 选中所有带有id属性的a标签(处理非唯一id的情况) const anchorElements = document.querySelectorAll('a[id]'); // 遍历每个元素进行修改 anchorElements.forEach(anchor => { const targetId = anchor.id; // 拼接固定域名和id锚点 anchor.href = `https://www.exampledomain/testpage.aspx#${targetId}`; // 可选:如果不需要保留原来的id属性,可以移除 // anchor.removeAttribute('id'); });
jQuery方案
如果你项目里已经引入了jQuery,用它的遍历方法会更简洁:
// 选中所有带有id属性的a标签 $('a[id]').each(function() { const targetId = $(this).attr('id'); // 设置href属性 $(this).attr('href', `https://www.exampledomain/testpage.aspx#${targetId}`); // 可选:移除原id属性 // $(this).removeAttr('id'); });
关键说明
- 因为
id是非唯一的,所以不能用getElementById(它只会返回第一个匹配的元素),必须用querySelectorAll(原生)或$('a[id]')(jQuery)选中所有符合条件的标签。 - 固定域名直接拼接到锚点前即可,动态
id通过元素的属性获取后拼接在#后面。
内容的提问来源于stack exchange,提问作者Notary Classes
相关产品推荐
相关产品推荐

