How to match element?

2019-07-15 07:47发布

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/

6条回答
你好瞎i
2楼-- · 2019-07-15 08:28

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 ...
}
查看更多
干净又极端
3楼-- · 2019-07-15 08:33

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/

查看更多
小情绪 Triste *
4楼-- · 2019-07-15 08:36
$('.main-menu li a').each(function() {
     if( MainMenu == $(this).attr() ) $(this).addClass('active');
});
查看更多
孤傲高冷的网名
5楼-- · 2019-07-15 08:37

Use the attribute selector.

item = $('.main-menu > li > a[href="' + MainMenu + '"]');

http://api.jquery.com/attribute-equals-selector/

查看更多
姐就是有狂的资本
6楼-- · 2019-07-15 08:38

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/

查看更多
够拽才男人
7楼-- · 2019-07-15 08:46
        $(".main-menu > li > a[href^='" + MainMenu + "']");
        $(".sub-menu > li > a[href$='" + SubMenu + "']");
查看更多
登录 后发表回答