1

我对 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" 添加到最终结果中。这是不好的做法还是可以接受的?

感谢您的任何建议。

4

1 回答 1

0

您可以检查是否以 .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因此他们的目标将被设定。

于 2010-03-05T01:17:11.910 回答