1

有没有一种很好的方式来检查被点击的链接的 URL 是否指向另一个主机?

$(document).ready(function() {
    $('a[target="_blank"]').click(function() {
        if (confirm('This link will open in an new window.')) {
            return true;
        } else {
            return false;
        }
    });
});

我不能依靠 CMS 来过滤指向另一台主机的每个链接并添加属性target="_blank"。所以我想测试点击链接的 URL,我认为这是一个更强大的测试。

我知道我可以编写一些自定义代码来测试各种string starts with场景。但是是否已经有一个很好的 jQuery(或其他)功能呢?

解决方案:

谢谢你的帮助!我应用了这个解决方案:

$(document).ready(function() {
    $('a').click(function() {
        if (this.host != location.host) {
            $(this).attr('target', '_blank'); // add or override the attribute (in case there isn't one already)
            return confirm('This link will open in an new window.');
        }
    });
});

顺便说一句:我只会在网站处于移动模式(使用modernizr)时使用此代码。所以我可以包装应用程序PhoneGap并防止用户在某个随机站点上处于全屏模式而无法返回。

4

4 回答 4

3

您可以location.host与 Anchor 元素的host.

$('a').click(function() {
  if (this.host != location.host && confirm('This link will open in an new window.')) {
    $(this).attr('target', "_blank");
  }
  // don't need else, let it be the default behavior of anchor
  // if you don't want to jump to the new page, then add else return false
});
于 2012-09-28T03:15:23.243 回答
1

您可以检查host链接的属性以查看它是否与当前网站的主机匹配。

$('a').click(function() {
  if (this.host != window.location.host) {
     // do something like
     $(this).attr('target', "_blank");
  } else {
     // do something else
  }
});
于 2012-09-28T03:09:36.070 回答
0

见现场小提琴

通常外部链接会开始,http:// 所以试试这个

 $('a[href^="http://"],a[href^="https://"]').on('click', function(){
     if (confirm('This link will open in an new window.')) {
            return true;
        } else {
            return false;
        }

});
于 2012-09-28T03:09:06.163 回答
0

您可以为页面上的每个链接添加点击处理程序:

jQuery('a').click(function() {
  if (this.href.indexOf('http://') == 0) {
    return confirm('Leaving, OK?');
  }
});

但这会给很多元素添加事件处理程序,并且可能效率低下。

更有效的方法是在文档中添加一个点击处理程序。点击 A 标签会冒泡,您可以一举抓住它们。像:

jQuery(document).click(function(e) {
  if (e.target.tagName == 'A') {
    if (e.target.href.indexOf('http://') == 0) {
      return confirm('Leaving, OK?');
    }
});

对于您实际的“外部”检查,您当然需要“http://”或“https://”。

编辑:

我想我更喜欢@hsalama 的回答。虽然我会将其更改为:

jQuery('a[href^="http://"]').add('a[href^="https://"]').click(function() {
  return confirm('This link will open in an new window.');
});

顺便说一句,做:

if (condition) {
  return true;
} else {
  return false;
}

只会让你被其他程序员取笑。只是:

return condition;
于 2012-09-28T03:13:29.667 回答