![](/img/trans.png)
[英]Best way to overwride all target=“_blank” to open links on same page
[英]Will Firefox not “correctly” open links with a target=“_blank” attribute added on page load by JavaScript?
我正在使用以下代码(带有Underscore.js库)将属性target="_blank"
和rel="external"
到页面加载时的所有非本地链接中。 我的代码如下所示:
(function($){
$(document).ready(function(){
// Create a matching regex pattern based on current host name
var regexPattern = new RegExp(location.origin);
// Gather all non-local links
nonLocalLinks = _(jQuery('a')).reject(function(link) {
return link.href.match(regexPattern);
});
// Add attributes to all non-local links
_(nonLocalLinks).each(function(item) {
item.target = '_blank';
item.rel = 'external';
});
})
})(jQuery)
此代码在所有经过测试的浏览器(Chrome 17,IE7,IE8,IE9,Safari)中均能正常运行,但在Firefox 10中不起作用。链接是在锚标签上设置了target="_blank"
属性作为HTML输出的一部分的链接,服务器功能符合预期。 这在Firefox中的页面加载上不起作用吗,还是我还缺少其他功能?
另外-非常感谢您提供的所有意见,但请不要暗示这是糟糕的用户体验,等等。我同意,但是我别无选择-这是针对客户的,这就是他们想要的。 “否”不是一个选择。
编辑:此“不起作用”意味着该链接在同一选项卡中打开。 firebug控制台中没有错误-链接的行为就像没有设置target="_blank"
。
Firefox在window.location
上没有origin
属性。 这意味着您的regexPattern
最终将//
regexPattern
下来,并且使nonLocalLinks
空。
演示(观看控制台): http : //jsfiddle.net/ambiguous/tS4WB/
您必须使用以下内容说明缺少的location.origin
:
var origin = location.origin;
if(!origin)
origin = location.protocol + '//' + location.host;
演示: http : //jsfiddle.net/ambiguous/envWe/
您可能还想在正则表达式中添加^
锚,或者仅检查indexOf
为您提供零。
如果您查看window.location
上的MDN文档 ,则会看到支持以下属性:
没有起源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.