2016-07-28 54 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> 

這裏是:

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

沒有activeclass當前URL。 ... element.Since股利是a使用children()find()方法內

回答

1

closest()方法是使用用於獲取的祖先。

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

或者select it based on the this context

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

雖然獲得當前頁面的URL使用window.location.href

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

或使用條件爲window.location.pathname == $(this).attr('href')

+0

我更新了我的問題,有不止一個網上檔案。 – lovepeople

+0

@lovepeople你想更新每一個網址....也改變你的條件爲'$ .trim(this.href)=='#'' –

+0

@lovepeople:也改變你的條件爲'$(this).attr 'href')=='#'' –

0

試試這個:

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

請注意,window.location是一個對象,而不是一個字符串