使用 jQuery 更改所有外部链接

Change all external links using jQuery

本文关键字:外部 链接 jQuery 使用      更新时间:2023-09-26

我想更改博客上的所有外部链接(blogspot在这里,这就是我寻找jQuery代码的原因),而不更改博客的发布,因为如果我这样做,我需要做很多工作。

例如,我的网站是example.com .我想将所有外部链接更改为

http://example.com/p/go.html?url=http://externallink.com

无需对我的博客文章进行任何更改。我没有任何想法可以开始。

已解决:https://gist.github.com/2342509 谢谢大家:D我只需要稍微改变一下。

在jQuery中,你可以尝试:

// DOM ready
$(function(){
    $('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});

当然,这只有在您在 HTML 中设置了 target="_blank" 属性/属性并且您希望所有链接打开相同的 url 时才有效。这个想法源于您希望在不同的选项卡/窗口中自动打开外部链接的事实。

如果这不是必需的功能,则可以以类似的方式使用自定义data-属性。唯一的区别是您需要循环每个链接,并从中获取数据。

// DOM ready
$(function(){
    $('a[data-href]').each(function(){
        var anc = $(this),
            href = anc.prop('href'),
            dataHref = anc.data('href');
        anc.prop('href', href + '?url=' + dataHref);
    });
});

网页示例:

<a href="http://example.com/p/go.html" data-href="http://externallink.com">external link</a>

现在,如果仍然不是您想要的,您可能需要添加更多信息。

离开@Tim Vermaelan的答案,你可以试试这个,这将检查每个不以你网站的URL开头的链接,而不依赖于它是target="_blank"

$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');