如何在选择子li时将父li类设置为活动状态

时间:2015-03-31 09:40:46

标签: javascript jquery html css

我有以下菜单结构。当选择了孩子li时,例如&#34;概述&#34;,我希望突出显示父li,在这种情况下&#34;关于我们&#34;。< / p>

<div class="navbar-collapse collapse">
  <ul class="nav navbar-nav navbar-right">
    <li class="drop"><a href="#" >Home</a></li>
    <li class="drop"><a href="#" >About Us</a>
      <ul class="drop-down">
        <li class="drop"><a href="#" class="active">Overview</a></li>
        <li class="drop"><a href="#" >Security</a></li>
        <li class="drop"><a href="#" class="active">Expertise</a></li>
        <li class="drop"><a href="#" >Process</a></li>
        <li class="drop"><a href="#" >Platform</a></li>
        <li class="drop"><a href="c#" >Careers</a></li>
      </ul>
    </li>
  </ul>
</div>

我尝试了以下但是它没有工作:

$(document).ready(function(){
    var pathname = window.location.pathname,
        page = pathname.split(/[/ ]+/).pop(),
        menuItems = $('.navbar-nav');
    menuItems.each(function(){
        var mi = $(this),
            miHrefs = mi.attr("href"),
            miParents = mi.parents('li.a');
        if(page == miHrefs) {
            miParents.addClass("active").siblings().removeClass('active');
        }
    });
});

2 个答案:

答案 0 :(得分:1)

我认为这会有所帮助,试试这个:

$("li a").on("click", function() {
   $(this).parent().parents("li").css("background-color","red");
});

答案 1 :(得分:0)

也许你可以试试:

HTML:

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav navbar-right">
        <li class="drop"><a href="#">Home</a>
        </li>
        <li class="drop"><a href="#">About Us</a>
            <ul class="drop-down">
                <li class="drop"><a href="/foo">Overview</a>
                </li>
                <li class="drop"><a href="#">Security</a>
                </li>
                <li class="drop"><a href="#">Expertise</a>
                </li>
                <li class="drop"><a href="#">Process</a>
                </li>
                <li class="drop"><a href="#">Platform</a>
                </li>
                <li class="drop"><a href="c#">Careers</a>
                </li>
            </ul>
        </li>
    </ul>
</div>

JS:

$(document).ready(function () {
    var pathname = window.location.pathname,
        //page = pathname.split(/[/ ]+/).pop(),
        page = "/foo";
    menuItems = $('.drop-down li a');
    menuItems.each(function () {
        var mi = $(this),
            miHrefs = mi.attr("href"),
            miParents = mi.closest('.drop-down').closest("li").find("a").not(".drop-down li a");
        if (page == miHrefs) {
            //miParents.addClass("active").siblings().removeClass('active');
            miParents.addClass("active");
            mi.addClass("active");
        }
    })
});
  

Live Demo


menuItems = $('.navbar-nav');正在定位您的主列表,而不是列表项,因此您的.each()循环只触发一次。