Ich versuche, dem entsprechenden Menülistenelement eine "aktive" Klasse (d. H. Klasse = "aktiv") hinzuzufügen, basierend auf der Seite, auf der sie sich befindet, sobald die Seite geladen wird. Unten ist mein Menü, wie es jetzt ist. Ich habe jeden Codeausschnitt ausprobiert, den ich in dieser Hinsicht finden konnte, und nichts funktioniert. Kann jemand bitte einfach erklären, wo und wie Sie diese Aufgabe in Javascript hinzufügen müssen?
<ul id="nav">
<li id="navhome"><a href="home.aspx">Home</a></li>
<li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
<li id="navdocso"><a href="docs.aspx">Documents</a></li>
<li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
<li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>
Hier ist ein Beispiel für das Javascript, das ich in meinem Head-Tag in meinem Site-Master einsetze. Was mache ich falsch?
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(function () {
$('li a').click(function (e) {
e.preventDefault();
$('a').removeClass('active');
$(this).addClass('active');
});
});
});
</script>
Der Grund, warum dies nicht funktioniert, ist, dass das Javascript ausgeführt wird. Dann wird die Seite neu geladen, wodurch die "aktive" Klasse aufgehoben wird. Was Sie wahrscheinlich tun möchten, ist etwas wie:
$(function(){
var current = location.pathname;
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
Es gibt einige Fälle, in denen dies nicht funktioniert (mehrere ähnlich gerichtete Links), aber ich denke, das könnte für Sie funktionieren.
jQuery(function($) {
var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
$('ul a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
.active, a.active {
color: red;
}
a {
color: #337ab7;
text-decoration: none;
}
li{
list-style:none;
}
<h3>Add Active Navigation Class to Menu Item</h3>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
</ul>
<h2><a href="http://www.sweet-web-design.com/examples/active-item/active-class.html">Live Demo</a></h2>
ES6-Version, die ordnungsgemäß funktioniert, wenn Sie einen Link zu "/ products" haben und über Unterprogramme verfügen, z.
let switchNavMenuItem = (menuItems) => {
var current = location.pathname
$.each(menuItems, (index, item) => {
$(item).removeClass('active')
if ((current.includes($(item).attr('href')) && $(item).attr('href') !== "/") || ($(item).attr('href') === "/" && current === "/")){
$(item).addClass('active')
}
})
}
$(document).ready(() => {
switchNavMenuItem($('#nav li a, #nav li link'))
})
var cururl = window.location.pathname;
var curpage = cururl.substr(cururl.lastIndexOf('/') + 1);
var hash = window.location.hash.substr(1);
if((curpage == "" || curpage == "/" || curpage == "admin") && hash=="")
{
//$("nav .navbar-nav > li:first-child").addClass("active");
}
else
{
$(".topmenu li").each(function()
{
$(this).removeClass("active");
});
if(hash != "")
$(".topmenu li a[href*='"+hash+"']").parents("li").addClass("active");
else
$(".topmenu li a[href*='"+curpage+"']").parents("li").addClass("active");
}
$(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
$( ".top-menu li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd)
$(this).addClass('active')
});
});
Rob.M hat es richtig verstanden.
Ich werde nur meine Lösung posten, da seine nicht wirklich für mich funktioniert hat. Ich habe eine kleine Veränderung im Vergleich zu ihm. vorausgesetzt, Sie haben unterschiedliche Pfade zu jedem Link.
(function() {
var current = location.pathname;
$('#navbar ul li a').each(function() {
var $this = $(this);
// we check comparison between current page and attribute redirection.
if ($this.attr('href') === current) {
$this.addClass('active');
}
});
})();
Wenn in Ihrem Menü die Klasse active
in li
hinzugefügt werden muss, müssen Sie den obigen Code verwenden.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).closest('li').addClass('active');
}
});
});
Ich weiß, es ist eine Weile her, dass diese Frage gestellt wurde. Hier ist die Antwort, die ohne jQuery funktioniert:
var activeNavlink = document.querySelectorAll('nav a[href^="/' + location.pathname.split("/")[1] + '"]');
activeNavlink[0].classList.add('active');
Hoffe das hilft.
$(function(){
//this returns the whole url
var current = window.location.href;
//this identifies the list you are targeting
$('#nav li a').each(function(){
var $this = $(this);
// if the current path is exactly like this link, make it active
if($this.attr('href') === current){
//this takes care of ul inside a ul, it opens and make active the selected li
$this.parents('.dropdown-menu').toggle();
$this.css('color', 'red');
}
})
});
Das hat perfekt für mich funktioniert.
$(function($) {
let url = window.location.href;
$('nav ul li a').each(function() {
if (this.href === url) {
$(this).addClass('active');
}
});
});
Dies sollte Ihre Aufgabe erfüllen: document.querySelector (a[href^='${location.pathname.split('/'[1])}']
). ClassName = 'active'
Keine der oben genannten Lösungen hat bei mir funktioniert. Endlich hat diese Javascript-Lösung funktioniert.
<script>
function setActive() {
linkObj = document.getElementById('premier-topnav').getElementsByTagName('a');
for(i=0;i<linkObj.length;i++) {
if(document.location.href.indexOf(linkObj[i].href)>=0) {
linkObj[i].classList.add("active");
}
}
}
window.onload = setActive;
</script>
premier-topnav ist die id von navbar div.
. aktive Klasse ist definiert als:
#premier-topnav .active {
color: brown;
}
Dieser auf Seite JS-Code ist zu 100% funktionsfähig. Geben Sie Ihre ID ein und genießen Sie es.
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(document).ready(function() {
var CurrentUrl= document.URL;
var CurrentUrlEnd = CurrentUrl.split('/').filter(Boolean).pop();
console.log(CurrentUrlEnd);
$( "#lu-ID li a" ).each(function() {
var ThisUrl = $(this).attr('href');
var ThisUrlEnd = ThisUrl.split('/').filter(Boolean).pop();
if(ThisUrlEnd == CurrentUrlEnd){
$(this).closest('li').addClass('active')
}
});
});