Self .active menu item
I have th开发者_如何学Pythone following script:
(function($) {
$.fn.MenuAutoActive = function() {
var menus = $('ul li a');
//menus.removeClass('active');
var matches = menus.filter(function() {
return document.location.href.indexOf($(this).attr('href')) >= 0;
});
matches.addClass('active');
};
What id does:
- it loop through all ul > li list in search for 'a'
- check 'a' for 'href'
- if href = current URL it adds class'active' to it
The only problem I have with it it looks only in last bit of the href:
for example: Main Menu will be:
<ul>
<li><a href="index.html"></a></li>
<li><a href="Services/index.html"></a></li>
<li><a href="Portfolio/index.html"></a></li>
<li><a href="Conact/index.html"></a></li>
</ul>
URL = http://www.website.com/Services/
In this case script WILL NOT mark the <a href="Services/index.html"></a>
as the URL does not contains index.html.
How can I make look in last ( after last / ) and one before last bit( before last / ) of the URL?
Any help much appreciated!
Pete
This should work:
return document.location.href.indexOf(this.href) >= 0;
Note that this accesses the href
property of the DOM element. This will return the absolute URL.
So this.href
will give you http://www.website.com/index.html
and not only index.html
.
try to replace
document.location.href.indexOf($(this).attr('href')) >0
by
document.location.toString().indexOf($(this).attr('href')) >0
var bits=$(this).attr('href').split('/');
var thelastbit=bits.pop();
var thepenultimatebit=bits.pop(); // previous call removed the last bit
May be quicker if you don't put index.html in the link in the first place or remove it while interrogating
return document.location.href.indexOf($(this).attr('href').replace('index.html','')) >= 0;
精彩评论