简体   繁体   中英

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.

For example, my website is 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.

In jQuery you can try:

// 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. 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. 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:

<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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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