如何使用JS自动在新窗口中打开外部链接(使用例外规则)?

时间:2018-01-08 14:33:51

标签: javascript class hyperlink rel nofollow

对于我的问题,我到目前为止无法找到解决方案。 我想要的是一个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时,它应该只执行示例脚本。

非常感谢和新年快乐!

1 个答案:

答案 0 :(得分:0)

我认为你应该使用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');
});
相关问题