2016-07-28 4 views
0

これにはほとんど3時間を費やしています。何も見つかりません。クラスを最寄りのdivに追加

ここに私のコードです..ファイルの3別のURL。 (更新)

<div id="menu"> 
<a href="blue.php"> 
<div class="list"> 
Content_here 
</div> 
</a> 

<a href="yallow.php"> 
<div class="list"> 
Content_here 
</div> 
</a> 

<a href="black.php"> 
<div class="list"> 
Content_here 
</div> 
</a> 
</div> 

は、ここで現在のURLに

<div id="menu"> 
<a href="#"> 
<div class="list active"> 
content_here 
</div> 
</a> 
</div> 

をクラスを追加します:現在のURL

$("#menu a").each(function(index) { 
    if($.trim(this.href) == window.location) { 
     $(this).closest('div').addClass("active"); 
    } 
}); 

ませんactiveclass。 div要素はa使用children()またはfind()メソッド内でelement.Since ...

答えて

1

closest()方法は、祖先を取得するために使用されます。

$(this).find('div').addClass("active"); 

またはselect it based on the this context


取得するために、現在のページのURLがwindow.location.hrefを使用していますが

$('div', this).addClass("active"); 

$("#menu a").each(function(index) { 
    if($.trim(this.href) == window.location.href) { 
     $('div', this).addClass("active"); 
    } 
}); 

またはこれを試してみてくださいwindow.location.pathname == $(this).attr('href')

+0

で、1以上があることに注意してくださいファイル上のURL。 – lovepeople

+0

@lovepeopleあなたはすべてのURLを更新したいと思います....また、条件を '$ .trim(this.href)== '#'' –

+0

に変更してください。@lovepeople:あなたの条件を '$(this).attr( 'href')== '#' ' –

0

などの条件を使用します。

$("[url="+window.location.origin+"]").addClass("active") 

window.locationがオブジェクトではなく、私は私の質問を更新した文字列

関連する問題