使用jQuery更改所有外部链接

时间:2015-03-07 06:43:55

标签: javascript jquery blogger

我想更改我博客上的所有外部链接(这里是blogspot,这就是为什么我要查找jQuery代码)而不更改我的博客发布,因为如果我需要做大量的工作这一点。

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

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

我的博客文章无需任何更改。我没有任何想法开始。

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

2 个答案:

答案 0 :(得分:1)

在jQuery中你可以尝试:

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

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

如果这不是必需的功能,您可以以类似的方式使用自定义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);
    });
});

HTML示例:

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

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

答案 1 :(得分:0)

关于@Tim Vermaelan的回答,您可以尝试这一点,这将检查每个不以您网站的网址开头的链接,而不依赖于target="_blank"

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