Selecting menu items using location.pathname + location.search
I ma using Javascript function to select menu items:
function selectActiveMenuItem() {
var path = location.pathname + location.search + location.hash;
var links = null;
links = $("a[href='" + path + "']");
links.parents("li").each(function () {
$(this).addClass('current').closest('li').addClass('current');
});
}
It is working strange - it doesn't work from the start when homepage is loaded. Homepage link in menu is not selected. I have to click on menu item (homepage or some other) and then it load page once again and right menu item is selected.
Previously I was using only开发者_运维问答: var path = location.pathname;
without location.search
and then it was working fine from the begining. But now my links are more complicated - they look for example like that: http://localhost//MainApp/User/Order.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=NMO
and other one is http://localhost//MainApp/User/Order.aspx?id=949abc91-a644-4a02-aebf-96da3ac7d8e1&type=MO
. So I have to use location.pathname + location.search
to make my function work.
Also I tried using var path = location.href.replace(/^.*\/\/[^\/]+/, '');
but the effect was the same as with var path = location.pathname + location.search;
- homepage was not selected in menu when page loaded.
The question: How to make homepage selected in menu when page is loaded?
Can you just use the [href^= ... ]
syntax to ignore the hash and query?
function selectActiveMenuItem() {
$('a[href=^' + location.pathname + ']').parents('li').each(function () {
$(this).addClass('current').closest('li').addClass('current');
});
}
I had to add checking home link. Now function works and it looks like that:
function selectActiveMenuItem() {
var path = location.pathname + location.search + location.hash;
var createhomelink = null;
var homepath = null;
var links = null;
createhomelink = path + "&from=user";
homepath = document.getElementById("home").href.replace(/^.*\/\/[^\/]+/, '');
if (createhomelink == homepath) {
path = createhomelink;
}
links = $("a[href='" + path + "']");
links.parents("li").each(function () {
$(this).addClass('current').closest('li').addClass('current');
});
}
精彩评论