简体   繁体   English

如何使用jQuery将.current类添加到父级li

[英]How to add .current class to parent li using jquery

I was wondering if someone can help me. 我想知道是否有人可以帮助我。 I trying to add .current class to the active parent in my navigation. 我试图在导航中将.current类添加到活动的父级中。

Here is my navigation: 这是我的导航:

<ul id="top-nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a>
    <ul id="about-dropdown" class="dropdown">
        <li><a href="#">Sub Cat</a></li>
        <li><a href="#">Sub Cat 1</a></li>
        <li><a href="#">Sub Cat 2</a></li>
    </ul>
</li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>

I have managed to get the .current class to display on the current page but when the user is on a sub page, eg. 我设法让.current类显示在当前页面上,但是当用户在子页面上时,例如。 "Sub Cat 1" I want the "About" a tag to add the .current page. “ Sub Cat 1”我想要“ About”标签添加.current页面。

Here is my Jquery: 这是我的Jquery:

 var url = window.location.pathname, 
 urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // create regexp to match current url pathname and remove trailing slash if present as it could collide with the link in navigation in case trailing slash wasn't present there
    // now grab every link from the navigation
    $('#top-nav a').each(function(){
        // and test its normalized href against the url pathname regexp
        if(urlRegExp.test(this.href.replace(/\/$/,''))){
            $(this).addClass('current');
        }

        $(document).ready(function(){
$("li.current").parent().addClass("current");
});

                $(document).ready(function(){
$("ul.current").parent().addClass("current-parent");
});

If anyone can help it would be appreciated :-) 如果有人可以帮助,将不胜感激:-)

Thanks 谢谢

I think what you want is the parents() function: 我认为您想要的是parent()函数:

$(document).ready(function(){
    $("li.current").parents('#top-nav > li').addClass("current");
});

If you only want the top level item use the selector above. 如果您只想要顶层项目,请使用上面的选择器。 If you want all parents use '#top-nav li' 如果您希望所有父母都使用'#top-nav li'

<ul id="top-nav">
<li><a href="#">Home</a></li>
<li><a href="#">About</a>
    <ul id="about-dropdown" class="dropdown">
        <li><a href="#">Sub Cat</a></li>
        <li><a href="#">Sub Cat 1</a></li>
        <li><a href="#">Sub Cat 2</a></li>
    </ul>
</li>
<li><a href="#">Blog</a></li>
<li><a href="#">Contact</a></li>
</ul>

JavaScript JavaScript的

$('#top-nav li a').hover(function(){
    $(this).addClass('current');
}).mouseleave(function(){
    $(this).removeClass('current');
});
$('#about-dropdown').hover(function(){
    $(this).prev().addClass('current');
}).mouseleave(function(){
    $(this).prev().removeClass('current');
});

CSS CSS

.current{
    background: #F00;
}

Fiddle 小提琴

http://jsfiddle.net/7LzLk8aw/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM