开发者

how to open outside links in a new tab

On my website i have many outside links, as well as internal links. i'd like some kind of solution in javascript or w/e that detects outside links and opens them in a new tab, but leaves internal link开发者_JAVA技巧s to be opened in the same tab. thanks! =)


function getXterlinks()
{
    var Xterlinks = document.getElementsByTagName('A');
    for (var i=0;i<Xterlinks.length;i++)
    { 
        var eachLink = Xterlinks[i];
        var regexp_isYourdomain="your-domain.com";
        var regexp_ishttp=/(http(.)*:\/\/)/;
        if( (eachLink.href != null) && (eachLink.href.match(regexp_isYourdomain) == null) && eachLink.href.match(regexp_ishttp)!=null )
        {
            eachLink.target ="_blank";
        }
    }
}

Source: http://www.mediawiki.org/wiki/Manual:Opening_external_links_in_a_new_window#How_to_make_external_links_open_in_a_new_window


Yeah, well, jQuery's still JavaScript. How about:

$('a[href^="http://your-domain.com"]').attr("target", "_self");

$('a').not('a[href^="http://your-domain.com"]').attr("target", "_blank");

Not sure about the second, though, but you get the idea.


I wrote this solution for my personal web site. As long as you like jQuery (which you should, imho), you can include this in a common js file and forget about it. It will work with dynamic content, and will not force internal links to open in the current tab if you set target="_blank".

$(function() {
    $('body').on('click', 'a', function() {
        var currentHost = document.location.protocol+'//'+document.location.hostname;
        if (this.href.indexOf(currentHost) != 0 && (this.href.indexOf('http') == 0 || this.href.indexOf('ftp') == 0)) {
            window.open(this.href, '_blank');
            return false;
        }
    });
});

Note: If you are using jQuery < 7, use .bind() instead of .on()

See it in action on http://www.seanknutson.com.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜