简体   繁体   English

使用jQuery将类添加到嵌套ul li中的top li元素

[英]adding class to top li element in nested ul li with jquery

I have following nested ul li tree structure 我有以下嵌套的ul li树结构

<ul id='main-menu'>
    <li>
        <a href=""><div>About Us</div></a>
        <ul>
            <li>
                <a href=""><div>Know Us</div></a>
            </li>
            <li>
                <a href=""><div>History</div></a>
                <ul>
                    <li>
                        <a href=""><div>Mission</div></a>
                    </li>
                    <li>
                        <a href=""><div>Vision</div></a>
                    </li>
                    <li>
                        <a href=""><div>Milestones</div></a>
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

So here top most li element is "About Us", what i want to do is when any child link of About US is opened i want to add class to About US li to show it is active, i have tried number different ways but not succeeded, can any one help me with this ? 因此,这里最重要的li元素是“关于我们”,我想做的是打开“关于我们”的任何子链接时,我想向“关于我们” li添加类以表明它是活动的,我尝试了几种不同的方法,但没有成功了,有人可以帮助我吗? i am knew to jquery 我知道要jQuery

You can add an id (for a simpler identification of the menu element) to your 'About us' link and on document.ready for each page that can be accessed from 'About us' menu, you will add a class to the 'About us' menu 您可以在“关于我们”链接和文档上添加一个id(以简化菜单元素的标识)。对于可以从“关于我们”菜单访问的每个页面,您都可以在“关于”中添加一个类我们的菜单

$( document ).ready(function() {
   $('#aboutUsLink').addClass('active-menu');
});

First of all you have to remember that each time you click on a particular link, your browser will load completely new page. 首先,您必须记住,每次单击特定链接时,浏览器将加载全新的页面。 So the best joice would be to add this "active" class on server side (php, ASP etc.) 因此,最好的选择是在服务器端添加此“活动”类(php,ASP等)。

But if you really have to add it on the browser side you could simply add to each of those web site a javascript with code: 但是,如果您真的必须在浏览器端添加它,则只需在每个网站上添加一个带有代码的javascript:

$(function(){
  var pageName = (window.location.href || '').trim().toLowerCase().match(/[^\/]+$/gm);
  var linkToThePage = $('a[href="'+pageName+'"]:first-of-type', $('#main-menu'));
  var allParentLi = linkToThePage.parents('li');
  allParentLi.addClass('selected');
});

I've implemented this here: https://plnkr.co/edit/Lwy8TQ8IFyadERkMzo71 我已经在这里实现了: https : //plnkr.co/edit/Lwy8TQ8IFyadERkMzo71

You can run it and click on "Vision" or "Milestones" links. 您可以运行它,然后单击“视觉”或“里程碑”链接。

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

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