如何使用JavaScript批量替换博客文章的跳转URL?
批量替换博客文章链接域名的实现方案
方法1:页面加载后批量替换现有链接
如果文章链接是页面加载时就渲染完成的,直接用JavaScript遍历所有链接并修改href属性即可:
document.addEventListener('DOMContentLoaded', () => { const oldPrefix = 'https://my-domain.com/'; const newPrefix = 'https://new-domain.com/blog/'; document.querySelectorAll('a').forEach(link => { const currentHref = link.getAttribute('href'); if (currentHref?.startsWith(oldPrefix)) { link.setAttribute('href', currentHref.replace(oldPrefix, newPrefix)); } }); });
这段代码会在页面DOM加载完成后,自动把所有以旧域名开头的链接替换为新格式,用户点击前看到的就是修改后的链接。
方法2:点击时实时替换(适配动态加载内容)
如果文章列表是动态加载的(比如滚动加载、异步分页),上面的方法无法覆盖后续生成的链接,这时用事件委托监听点击事件,实时处理:
document.addEventListener('click', (e) => { const targetLink = e.target.closest('a'); if (!targetLink) return; const currentHref = targetLink.getAttribute('href'); const oldPrefix = 'https://my-domain.com/'; const newPrefix = 'https://new-domain.com/blog/'; if (currentHref?.startsWith(oldPrefix)) { e.preventDefault(); window.location.href = currentHref.replace(oldPrefix, newPrefix); } });
这个方案会拦截所有<a>标签的点击,检查链接是否符合旧域名规则,符合则阻止默认跳转,替换为新链接后再跳转,动态生成的链接也能被覆盖。
适配相对路径的情况
如果你的文章链接是相对路径(比如/xyz-post),只需调整前缀匹配逻辑:
// 方法1适配相对路径 document.addEventListener('DOMContentLoaded', () => { const oldPrefix = '/'; const newPrefix = 'https://new-domain.com/blog/'; document.querySelectorAll('a').forEach(link => { const currentHref = link.getAttribute('href'); if (currentHref?.startsWith(oldPrefix)) { link.setAttribute('href', newPrefix + currentHref.slice(oldPrefix.length)); } }); });
你可以把上述代码放到博客主页的自定义脚本区域(比如主题设置的自定义JS栏、页面底部的<script>标签中),根据你使用的博客平台选择对应的添加位置即可。
内容的提问来源于stack exchange,提问作者Entronn
相关产品推荐
相关产品推荐

