对于我的问题,到目前为止我还没有找到解决方案。 我想要的是一个 js 脚本,它将转换我的网站(页面)上的所有外部链接,以便它们在新窗口中打开(将 target=_blank 添加到 a 标记)。
为此,我找到了一个简单的脚本来执行此操作,并且它的工作方式就像一个魅力(来源:gist.github.com/wpscholar)。但是,我根本无法控制输出。我认为对哪些链接被更改、哪些不被更改进行一些控制是有意义的。这是基本脚本:
/** Open all external links in a new window */
jQuery(document).ready(function($) {
$('a')
.filter('[href^="http"], [href^="//"]')
.not('[href*="' + window.location.host + '"]')
.attr('rel', 'nofollow noopener noreferrer')
.attr('target', '_blank');
});
任何人都可以给我一个关于如何在 a 标记具有 class=trusted 时添加异常的示例脚本吗?其中仅设置了 target 属性,rel 属性留空。
<a href="https://somedomain.com/" class="trusted">anchor</a>
变成:
<a href="https://somedomain.com/" class="trusted" target="_blank">anchor</a>
当没有找到 class=trusted 时,它应该只执行示例脚本。
非常感谢,新年快乐!
最佳答案
我认为你应该使用 not() 将你的类“trusted”添加到你的 jQuery 选择器中(就像你对 href 所做的那样):
/** Open all external links in a new window */
jQuery(document).ready(function($) {
$('a')
.filter('[href^="http"], [href^="//"]')
.not('[href*="' + window.location.host + '"]')
.attr('rel', 'nofollow noopener noreferrer')
.not('.trusted')
.attr('target', '_blank');
});
关于javascript - 如何使用JS自动在新窗口中打开外部链接(有异常(exception)规则)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48152420/