问题
I have the following html:
<!-- MainMenu -->
<ul class="main-menu">
<li><a href="About/xxxxx">About</a></li>
<li><a href="Services/xxxxx">Services</a></li>
<li><a href="Portfolio/xxxxx">Portfolio</a></li>
</ul>
<!-- /MainMenu -->
<!-- MainMenu -->
<ul class="sub-menu">
<li><a href="xxxxx/subpage1.html">About Main</a></li>
<li><a href="xxxxx/subpage2.html">About Main</a></li>
<li><a href="xxxxx/subpage3.html">About Main</a></li>
</ul>
<!-- /MainMenu -->
And following jQuery, which already cut URL into needed to matching bits.
$(document).ready(function() {
urlParts = "www.website.com/About/subpage1.html".split("/")
var MainMenu = urlParts[1]+"/"; // mainmenu e.g About/XXXX
var SubMenu = urlParts[2]; //submenu e.g XXXX/subpage1.html
// Find matched to var = MainMenu within main-menu > li > a
// Find matched to var = SubMenu within sub-menu > li > a
});
What I want to do:
- Find matched to var = MainMenu within main-menu > li > a and addClass('active') to matched 'a'
- Find matched to var = SubMenu within sub-menu > li > a and addClass('active') to matched 'a'
So how can run through those menus looking for matches to those var?
http://jsfiddle.net/MrTest/gWDm8/124/
回答1:
You can use the [name^="..."]
and [name$="..."]
selectors to match attributes that start and end with specific strings:
$('.main-menu > li > a[href^="'+MainMenu+'"], .sub-menu > li > a[href$="'+SubMenu+'"]')
.addClass('active');
Demo: http://jsfiddle.net/gWDm8/127/
回答2:
Use the attribute selector.
item = $('.main-menu > li > a[href="' + MainMenu + '"]');
http://api.jquery.com/attribute-equals-selector/
回答3:
$('.main-menu li a').each(function() {
if( MainMenu == $(this).attr() ) $(this).addClass('active');
});
回答4:
A simple but probably inaccurate solution is the usage of the :contains
pseudo selector:
$('ul.main-menu').find('li:has(a:contains(' + MainMenu + '))').addClass('active');
That will add the class active
to the parent li node
which contains an anchor
, which contains the string. More accurate is an exact matching:
$('ul.main-menu, ul.sub-menu').find('a').each(function(_, anchor) {
var $anchor = $(anchor),
parts = $anchor.attr('href').split(/\//);
if( parts[0] === MainMenu || parts[1].indexOf(SubMenu) > -1 ) {
$anchor.addClass('active');
}
});
http://jsfiddle.net/MKH3Y/
回答5:
You can assign ids or classes to each element and go one by one, or you can use .each
.
For instance:
$("ul > li").each(function(){
... your code ...
}
回答6:
$(".main-menu > li > a[href^='" + MainMenu + "']");
$(".sub-menu > li > a[href$='" + SubMenu + "']");
来源:https://stackoverflow.com/questions/6610861/how-to-match-element