0

外部リンクを識別し、それらに「外部」クラスを追加するために、以下のコードを書きました。これを自分のサイトに実装しました。正常に動作していますが、「タブ」と「コメントに返信」オプションで正しく動作しない問題が 1 つあります。そこに「外部」クラスを追加していますが、それらはローカルリンクです。コードに問題がある場合はお知らせください。

タブのリンクは次のようになります。<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');
        }
    }
});
4

1 に答える 1

6

属性を取得する代わりに、プロパティを取得します。

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/

于 2013-06-16T05:15:05.500 に答える