2

我们目前有一些通过我们的跟踪软件的 php 重定向,我想在访问者浏览器的新选项卡中打开它们,但不想通过整个站点手动添加target="_blank"rel=external.

我们当前的链接看起来像这样

<a href="http://www.website-shown-browser.com" onclick="this.href='http://'+window.location.host+'/visit/redirect.php'">Website</a>

我看到了一些 jQuery 代码示例,它们根据域 url 自动识别外部链接,但是我们正在使用我们在域上托管的这些重定向,因此这些链接将被过滤掉。

4

1 回答 1

5

与手动添加相比,这是可能的,但不一定有效。您将选择所有 a 标签并检查它们的 href 是否是外部的。target然后,如果它是,您将_blank为该元素设置属性:

$('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');
       });
   }
});

一种更有效的方法是调整您的选择器以仅选择以 开头的标签http://,但这仅在您的内部链接没有前缀时才有效http://

$("#content a[href^='http://']").attr("target","_blank");
于 2012-07-22T02:47:12.007 回答