2016-07-28 16 views
0

Fast 3 Stunden verbringen, um dies zu verbringen. Nichts gefunden.Add Klasse, am nächsten div

Hier ist mein Code .. 3 separate URL in der Datei. (Aktualisiert)

<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> 

Add-Klasse auf aktuelle URL

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

hier:

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

Kein activeclass zu aktuellen URL. ...

Antwort

1

Die closest() Methode für das Erhalten der Vorfahren verwendet element.Since die div in der a Verwendung ist children() oder find() Methode.

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

Oder select it based on the this context.

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

Obwohl die aktuelle URL Seite window.location.href verwenden für immer.

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

oder Gebrauchszustand als window.location.pathname == $(this).attr('href')

+0

ich meine Frage aktualisiert, gibt es mehr als ein URL in Datei – lovepeople

+0

@lovepeople Sie möchten jede URL aktualisieren .... ändern Sie auch Ihre Bedingung in '$ .trim (this.href) == '#'' –

+0

@lovepeople: Ändern Sie auch Ihre Bedingung zu '$ (this) .attr ('href') == '#' ' –

0

try this:

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

Bitte beachten Sie, dass window.location ein Objekt und kein String