jQuery将_blank添加到外部链接

Zol*_*tan 2 jquery

我正在创建一个脚本,自动将广告target ="_ blank"发布到所有外部链接.问题是,该脚本还会在新选项卡中打开内部绝对链接.您可以在此测试链接上查看问题:http: //www.fairfood.org/testtest/

$("a").filter(function () {
    return this.hostname && this.hostname !== location.hostname;
}).each(function () {
    $(this).attr({
        target: "_blank",
        title: "Visit " + this.href + " (click to open in a new window)"
    });
});
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决这个问题吗?

任何帮助深表感谢.

Lig*_*ica 10

www.yourhost.com是不一样的yourhost.com,所以当你的链接不匹配时,这是行不通的.

www.如果您知道这将始终导致有效的URI,您可以取出.

(另外,你的使用几乎.each是多余的,因为jQuery已经了解了元素集;但是,你需要它.只需要注意一些事情.)this.href

$("a").filter(function() {
    return this.hostname &&
           this.hostname.replace(/^www\./, '') !==
              location.hostname.replace(/^www\./, '');
}).each(function() {
   $(this).attr({
       target: "_blank",
       title: "Visit " + this.href + " (click to open in a new window)"
    });
});
Run Code Online (Sandbox Code Playgroud)

实例.