问题
I try to use jquery to initialize active class from navigation, but so far it works only if there's nothing else after the menu item in url.
For ex, if i go on users site.com/users the code works, but when i browse the controller and i give it parameters it disappears ex site.com/users/param1/param2
below you can see my code:
$(document).ready(function () {
var url = window.location;
// Will only work if string in href matches with location
$('ul.nav a[href="' + url + '"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});
回答1:
So lets say you have urls in this format /AAA/BBB/CCC/.... so this code will make your link to recognize all of the links /AAA/BBB/... and /AAA/XXX/....and such as same page.
$(document).ready(function () {
var url = window.location;
// this will break your url and put parts in array for
// first item is the one you call it page
var urlParts = url.split("/");
// will work only on links like /AAA
$('ul.nav a[href="' + urlParts[0] + '"]').parent().addClass('active');
// so we need to use custom filters
$('ul.nav a').filter(function () {
var hrefParts = this.href.split("/");
return hrefParts[0]==urlParts[0];// so you need to check if they should be 0 or 1 based on how your links are like: /AAA/ or AAA
// also in case your links are like absolute paths you need more effort.
}).parent().addClass('active').parent().parent().addClass('active');
});
Edited: Now should work. But you need to play with it. So this is the whole idea I think you can do it like check link types you have and based on your situation you should change things in your code.
回答2:
try this:
$('ul.nav a').filter(function () {
return url.href.indexOf(this.href) >= 0;
}).parent().addClass('active').parent().parent().addClass('active');
来源:https://stackoverflow.com/questions/49184660/bootstrap-navbar-active-class