简体   繁体   English

使用jQuery更改所有外部链接

[英]Change all external links using jQuery

I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that. 我想更改博客上的所有外部链接(此处是博客,这就是为什么我要查找jQuery代码)而不更改博客的发布,因为如果这样做,我需要做很多工作。

For example, my website is example.com . 例如,我的网站是example.com I want to change all external links to 我想将所有外部链接更改为

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

without need for any changes on my blog post. 无需对我的博客文章进行任何更改。 I don't have any idea to start with. 我没有任何想法开始。

SOLVED: https://gist.github.com/2342509 Thanks everyone :DI just need to change it a bit. 解决: https : //gist.github.com/2342509谢谢大家:DI只需稍作更改即可。

In jQuery you can try: 在jQuery中,您可以尝试:

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

Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. 当然,仅当您在HTML中设置了target="_blank"属性/属性并且希望所有链接都打开相同的网址时,这才起作用。 This idea derives from the fact you want to have external links open automatically in a different tab/window. 这个想法源于您希望在其他选项卡/窗口中自动打开外部链接的事实。

If this is not the required functionality, you can use a custom data- attribute in a similar way. 如果这不是必需的功能,则可以类似的方式使用自定义data-属性。 Only difference is you will need to loop each link, and get the data from it. 唯一的区别是您将需要循环每个链接,并从中获取数据。

// 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 example: HTML示例:

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

And now you will probably need to add more information if that is still not what you want. 现在,如果您仍然不想要这些信息,则可能需要添加更多信息。

摆脱@Tim Vermaelan的回答,您可以尝试使用此方法,它将检查不以您的网站URL开头的每个链接,而无需依赖于它是target="_blank"

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM