在新窗口中打开外部链接

时间:2025-01-20 14:48:29

HTNL属性:

<a href="/?spm=1001.2101.3001.4477" target="_blank">This link will open in new window/tab</a>

内联JavaScript方式:

<a href="/?spm=1001.2101.3001.4477" onclick="(); return false;" onkeypress="(); return false;">This link will open in new window/tab</a>

使用jQuery:

  1. $('a').each(function() {
  2. var a = new RegExp('/' + window.location.host + '/');
  3. if(!a.test(this.href)) {
  4. $(this).click(function(event) {
  5. event.preventDefault();
  6. event.stopPropagation();
  7. window.open(this.href, '_blank');
  8. });
  9. }
  10. });

您可以直接使用 HTML完成此操作,但这是无效标记,它可以处理业务而没有无效代码和不必要的标记。或者,您仍然可以避免验证问题,只需将 class target=_blank 内容附加到具有以 http:// 开头的 href 属性的任何链接。下面的示例仅针对 #content 区域中的链接。如果您的菜单是动态的并创建完整的 URL,像这样缩小范围可能是一个好主意。

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