【问题标题】:Open external links in new tab but exclude certain links在新选项卡中打开外部链接,但排除某些链接
【发布时间】:2019-04-13 06:04:05
【问题描述】:

我从某个地方找到了以下代码,它假设在新选项卡中打开外部链接,它工作正常。

我现在面临的问题,“滚动到顶部”按钮也会打开新标签并加载一个空白页面。滚动到顶部按钮没有 href 但有一个 ID。如何排除代码中的元素ID?

jQuery(document).ready(function($) {
    $('a').each(function() {
        var a = new RegExp('/' + window.location.host + '/');
        if(!a.test(this.href)) {
            $(this).click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                window.open(this.href, '_blank');
            });
        }
    });
});

【问题讨论】:

  • 您可以使用:not(请参阅 jQuery 选择器文档)。或者您可以为外部链接指定一个特定的类,并将此代码更改为仅选择该类而不是所有 a 元素

标签: jquery


【解决方案1】:

你可以使用not选择器(如果链接的id是top_link_id

$("a:not(#top_link_id)").each...

或者

   $("a").not("top_link_id").each...

【讨论】:

  • 非常感谢!我没有那样想!这是我解决问题的最终代码: jQuery(document).ready(function($) { $("a:not(#ast-scroll-top)").each(function() { var a = new RegExp( '/' + window.location.host + '/'); if(!a.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation( ); window.open(this.href, '_blank'); }); } }); });
  • 对不起,我不知道如何格式化评论中的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-12
相关资源
最近更新 更多