2016-12-18 111 views
0

我目前正在嘗試根據顯示的url設置活動div。jquery將活動類添加到所有div,但只想要活動的一個

此代碼適用於不是索引的所有內容。在索引上,它將活動類標記放到所有div上。 Here is a jsfiddle

.navigation a.active-link { 
    background-border: #red; 
    border-style: solid; 
    border-bottom: solid white; 
    color: black; 
    padding:10px; 
} 
#navigation a { 
    line-height:26px; 
} 
#navigation { 
    border-bottom: 1px solid currentColor; 
    text-decoration: none; 
    word-wrap: break-word; 
    padding-top: 10px; 
    margin-bottom: 15px; 
    overflow: hidden !important; 
    white-space: no-wrap; 
    text-overflow: clip; 
    height: 26px; 
    padding-bottom:26px; 
} 


<div class="navigation" id="navigation"> 
    <a href="/">Show all</a> 
    <a href="/ab/domains/" >.ab</a> 
    <a href="/ac/domains/" >.ad</a> 
    <a href="/ad/domains/" >.ac</a> 
</div> 


$(document).ready(function() { 
var pathname = window.location.pathname; 
$('#navigation').find('a[href$="' + pathname + '"]').addClass("active-link"); 

}) 

回答

0

那麼,你的指數是/因爲你的類添加到其href屬性與當前pathname這是/和所有環節結束時結束的所有環節與/)它是有道理的。

在您提供您可以定位是等於路徑名的元素,而不是結束,與

$('#navigation').find('a[href="' + pathname + '"]').addClass("active-link") 
0

我在頁面中使用這樣的: 添加類家裏索引鏈接,你必須在它的HREF使用「指數」二字。

<a href="/index">show all</a> 

那麼這樣的:

 var curruntLocation = window.location.href; 
     var linkFounded = false; 
     $('#navigation a').each(function() 
     { 
      var thisHref = $(this).attr('href'); 
      if (curruntLocation.indexOf(thisHref) > 0) 
      { 
       $(this).addClass('active-Link'); 
       linkFounded = true; 
      } 
     }); 

     if (!linkFounded)// we are in index page 
     { 
       $('a.home').addClass('active Link'); 
     } 
0

我希望我正確地理解你的問題的例子。您可以使用直接後代組合符(>)選擇您希望添加類的div。

一個例子是:

jQuery('#nav li > a');

您可以將IDS你一個

我沒有那麼多的jQuery的傢伙,但我希望幫助

相關問題