【问题标题】:Jquery External Link HelpJquery 外部链接帮助
【发布时间】:2011-01-23 19:40:08
【问题描述】:

我对 jquery 还很陌生,没有太多时间去探索更多内容,想知道是否有人可以帮助我。这是我从不同地方提取的代码:

$("a").filter(function() {
                         return this.hostname && this.hostname !== location.hostname;
                         })
                         .attr({
                                target: "_blank"
                               });
                         $('a[rel*="external"]').live('click',function(){ this.target='_blank'; });

我所做的是每当有一个带有 href="http://" 的 A 标签时,它就会向它添加 target="_blank" 。如果 href="http://" 后跟您所在的网站 URL,则不会添加 target="_blank"。最重要的是,如果我想在新窗口中打开内部页面,那么我会将 rel="external" 添加到 A 标签,然后在实时网站上将其转换为 target="_blank"。

我怎样才能做到这样,如果我有一个子域,它也不会作为外部页面打开。假设我的 url 是 example.com,子域是 test.example.com。因此,如果我创建了从 example.com 到 test.example.com 的链接,那么我不希望它在新窗口中打开。同样从 test.example.com 到 example.com 我也不希望它在新窗口中打开。

这也是一个好方法吗?我用 xhtml 1.1 编写我的网站并尝试保持页面有效。这将通过验证,但仍将 target="_blank" 添加到最终结果中。这是不好的做法还是可以接受?

感谢您的建议。

【问题讨论】:

  • 是的,这很好。页面应该通过验证之前 JavaScript 运行,而不是之后
  • 我认为在 JavaScript 运行后验证您的页面仍然是一种很好的做法。您可以在此处使用运行window.open($(this).attr('href'), '_blank')click()。它仍然使用 _blank 名称,但不会将属性添加到您的 HTML。

标签: jquery subdomain external hyperlink target


【解决方案1】:

您可以检查this.hostname 是否以location.hostname 结尾,而不是检查主机名是否相等。不幸的是,JavaScript 没有 endWith 函数,但您可以轻松编写一个:

String.prototype.endsWith = function(that) {
    return this.lastIndexOf(that) == this.length - that.length;
};

然后,在您的filter 方法中:

return this.hostname && this.hostname.endsWith(location.hostname);

指向subdomain.example.com 的链接以example.com 结尾,因此将设置它们的目标。

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2010-11-17
    • 2011-10-18
    • 2011-01-01
    相关资源
    最近更新 更多