在jQuery中使用相对路径识别链接



我写了下面的代码来识别外部链接,然后给它们添加"external"类。我在我的网站上实现了这一点,它工作得很好,但有一个问题,它不能正常工作的"标签"one_answers"回复评论"选项。它添加了"外部"类,但它们是本地链接。如果我的代码有问题,请告诉我。

标签的链接如下:<a href="#tab2" class="external">Popular</a>

和回复链接如下:<a class="comment-reply-link external" href="/samsung-galaxy-ace-plus-s7500-how-to-root-and-install-custom-recovery-image/?replytocom=1044#respond" onclick="return addComment.moveForm(&quot;comment-1044&quot;, &quot;1044&quot;, &quot;respond&quot;, &quot;420&quot;)">Reply</a>

我知道它失败了,因为这些不是绝对链接,所以location.host不会为这些链接工作。你能告诉我如何合并这些链接并添加"本地"类吗?

jQuery(document).ready(function ($) {
var root = new RegExp(location.host);
$('a').each(function(){
    if(root.test($(this).attr('href'))){ 
        $(this).addClass('local');
    }
    else{
        // a link that does not contain the current host
        var url = $(this).attr('href');
        if(url.length > 1)
        {
            $(this).addClass('external');
        }
    }
});

不获取属性,而是获取属性:

var url = $(this).prop('href');

或:

var url = this.href;

区别很重要:

> $('<a href="#bar">foo</a>').prop('href')
"http://stackoverflow.com/questions/17130384/identify-links-with-relative-path-in-jquery#bar"
> $('<a href="#bar">foo</a>').attr('href')
"#bar"

另外,我将使用location.origin而不是location.host:

$('a').filter(function() {
    return this.href.indexOf(location.origin) === 0;
}).addClass('local');

演示:http://jsfiddle.net/q6P4W/

最新更新