如何使用JavaScript更改所有外部链接? [英] How to change all external links with Javascript?

查看:88
本文介绍了如何使用JavaScript更改所有外部链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java脚本替换所有外部链接. 我只想在每个外部链接之前添加" http://example.com/go= . . 我该怎么做? 请帮助.

I want to replace all my external links using Javascript.. I just want to add "http://example.com/go=" before every external links... How will I do that? Please help..

推荐答案

以下代码段应该有效.它遍历所有<a>元素,并检查href是否包含当前域(我使用RegExp对其进行了测试,但也有一些可行的解决方案).如果没有,则添加前缀.

The following snippet should work. It iterates over all <a> elements and checks if the href contains the current domain (I test it using an RegExp, but there's also solutions thinkable as well). If not, the prefix is added.

const originReg = new RegExp(location.hostname, 'i');

document.querySelectorAll('a').forEach(a => {
  if (originReg.test(a.href)) return /* internal link */;
  
  a.href = `http://example.com/go?url=${encodeURI(a.href)}`;
});

<a href="/bar">Bar</a>
<a href="baz">Baz</a>
<a href="http://example.com/foo">Foo</a>

这篇关于如何使用JavaScript更改所有外部链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆