在网页开发中,经常需要控制链接的打开方式。对于外部链接(指向其他网站的链接),通常希望它们在新窗口或新标签页中打开,以保持用户在当前网站的浏览状态。
以下是使用jQuery实现这一功能的完整代码示例:
$(document).ready(function() {
// 选择所有外部链接
$('a[href^="http://"], a[href^="https://"]').not('[href*="' + window.location.host + '"]').attr('target', '_blank');
// 或者更精确的版本
$('a').each(function() {
var href = $(this).attr('href');
if (href && href.indexOf('http') === 0 && this.hostname !== window.location.hostname) {
$(this).attr('target', '_blank');
// 可选:添加rel="noopener noreferrer"增强安全性
$(this).attr('rel', 'noopener noreferrer');
}
});
});
$(document).ready()
确保DOM完全加载后再执行脚本a[href^="http://"], a[href^="https://"]
选择所有以http或https开头的链接.not('[href*="' + window.location.host + '"]')
排除当前域名的链接.attr('target', '_blank')
设置这些链接在新窗口打开rel="noopener noreferrer"
,防止新窗口通过window.opener
访问原始页面each()
循环可能比属性选择器更高效问题1:为什么有些外部链接没有在新窗口打开?
//example.com
)问题2:如何排除特定域名的链接?
$('a').each(function() {
var href = $(this).attr('href');
if (href && href.indexOf('http') === 0 &&
this.hostname !== window.location.hostname &&
this.hostname !== 'excluded-domain.com') {
$(this).attr('target', '_blank');
}
});
问题3:如何在链接后添加外部链接图标?
$('a[target="_blank"]').after('<span class="external-icon">↗</span>');
这个解决方案简单有效,可以轻松集成到任何使用jQuery的网站中。