为在新窗口中打开外部链接创建异常

Creating an exception for opening external links in new windows

本文关键字:创建 异常 链接 外部 在新窗口中打开      更新时间:2023-09-26

我使用一个简单的Jquery脚本在所有外部链接上强制target="_blank"。问题是它在新窗口中打开了子域。我想调整这个代码,这样它就可以在同一个浏览器会话中使用子域,而不是强制使用一个新窗口。

例如,如果我的网站http://pixeltest.com我有一个链接http://test.pixeltest.com,这将打开一个新的窗口。

代码:

$("a").filter(function() {
    return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');

有没有想过我该怎么做?

更改

return this.hostname && this.hostname !== location.hostname;

return this.hostname && this.hostname.substr(this.hostname.indexOf('.')) !== location.hostname.substr(location.hostname.indexOf('.'));

这只能比较第一个点之后的所有内容。