一般使用HTML代码在新窗口打开外部链接,都是用属性(target=”_blank”)。我们一般都希望在新窗口打开外部链接,这样用户就不需要离开网站就能访问外部链接,但是如果每个外部链接都手工加上新窗口打开的属性(target=”_blank”)的话,会让做网站的效率非常低。使用 jQuery,我们只需要几行代码就能在新窗口中打开外部链接。

1. 找到外部链接

首先我们需要找到所有的外部链接,在 $(document).ready() 函数添加如下代码:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])");

  
上面这段代码查找 href 属性是以 http:// 或者 https:// 开始的,并且不包含当前域名(location.hostname)的链接(a)标签。这样我们就不会获取任何相对路径或者绝对连接中含有当前域名的内部连接。

2. 给外部链接加上 “external” class

如果我们想给外部链接加上 “external” class,添加如下的代码:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external");

  
上面的代码给外部链接加上一个 “external” Class ,这样就可以使用 CSS 来样式化外部链接了。

3. 让外部链接在新窗口打开

如果你想外部链接在新窗口打开,继续增加如下一行代码:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external")
.attr("target","_blank");

  
上面的代码给链接标签增加一个 target 属性,并且给他赋值为 _blank,这样外部链接就能在新窗口打开。