在新窗口中打开外部链接

Avatar of Chris Coyier
Chris Coyier
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

你可以使用 HTML 直接完成,但这属于无效的标记,此方法可以在不使用无效代码和不必要标记的情况下完成任务。

或者,你仍然可以避免验证问题,只需将 class target=_blank 附加到 href 属性以 http:// 开头的任何链接上。下面的示例仅针对 #content 区域中的链接。如果你的菜单是动态的并创建完整的 URL,那么这样的限定可能是个好主意。

$("#content a[href^='http://']").attr("target","_blank");

另请注意,有许多不同的方法可以 仅定位外部链接