You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JS实现外部链接自动在新窗口打开并添加例外规则?

解决方案:给外部链接加新窗口打开规则,同时支持信任类例外

嘿,这个需求很好实现,我们只需要把原脚本的逻辑拆分成两部分,分别处理带trusted类的外部链接和普通外部链接,就能精准控制不同链接的属性设置啦。

下面是修改后的完整脚本:

/** Open all external links in a new window with trusted link exceptions */
jQuery(document).ready(function($) {
  // 处理带trusted类的外部链接:仅添加target="_blank"
  $('a.trusted')
    .filter('[href^="http"], [href^="//"]')
    .not('[href*="' + window.location.host + '"]')
    .attr('target', '_blank');

  // 处理普通外部链接:添加target和rel属性
  $('a')
    .not('.trusted') // 排除已处理的信任链接
    .filter('[href^="http"], [href^="//"]')
    .not('[href*="' + window.location.host + '"]')
    .attr('rel', 'nofollow noopener noreferrer')
    .attr('target', '_blank');
});

逻辑说明:

  • 第一块代码专门选中带trusted类的<a>标签,先筛选出外部链接(排除当前域名的链接),然后只给它们加上target="_blank",完全不碰rel属性,正好匹配你要的例外规则。
  • 第二块代码处理剩下的普通外部链接:先通过.not('.trusted')排除已经处理过的信任链接,再执行原脚本的逻辑,同时添加rel和target属性,保证原有的功能不受影响。

拿你的示例测试一下:

原链接:<a href="https://somedomain.com/" class="trusted">anchor</a>
处理后:<a href="https://somedomain.com/" class="trusted" target="_blank">anchor</a>

完全符合预期~ 普通外部链接则会保留原脚本的rel属性设置,新年快乐呀!

内容的提问来源于stack exchange,提问作者Emiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:37:59