将活动类添加到菜单项 [英] Add active class to menu item

查看:16
本文介绍了将活动类添加到菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Bootstrap 4 v6,我有以下导航:

我正在尝试在所选菜单项上设置活动类,但我所做的一切都没有奏效.

我最接近的是这段代码:

$(document).ready(function() {$('.navbar ul li').click(function(e) {$('.navbar ul li.active').removeClass('active');var $this = $(this);如果 (!$this.hasClass('active')) {$this.addClass('active');}e.preventDefault();});});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"crossorigin="anonymous"><script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin匿名"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx5Qin1Brankwx"cross<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkizqE+jo0ynG"cross></脚本><nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top"><button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="切换导航"><span class="navbar-toggler-icon"></span><a class="navbar-brand" href="#">DCH</a><div class="collapse navbar-collapse" id="navbarSupportedContent"><ul class="navbar-nav ml-auto"><li class="nav-item active"><a class="nav-link" href="index.php">首页</a><li class="nav-item dropdown"><a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">猫糖尿病</><div class="dropdown-menu bg-inverse navbar-inverse"><a class="dropdown-item" href="treatment.php">治疗</a><a class="dropdown-item" href="insulin.php">胰岛素和测试</a><a class="dropdown-item" href="relatedconditions.php">相关条件</a>

<li class="nav-item"><a class="nav-link" href="nutrition.php">Nutrition</a><li class="nav-item"><a class="nav-link" href="protocol.php">Protocol</a><li class="nav-item"><a class="nav-link" href="links.php">链接</a><li class="nav-item"><a class="nav-link" href="http://diabeticcathelp.com/forum" target="_blank">论坛</a><li class="nav-item"><a class="nav-link" href="contact.php">联系我们</a>

</nav>

它确实将活动类更改为单击的菜单项,但不会更改页面.它也不适用于子菜单项,但我认为我需要不同的代码来查看这些特定项是否被点击,而我还没有走那么远.首先,我想解决页面切换问题.如果我删除 e.preventDefault() 调用,则页面会移动,但菜单项不会更改为活动状态.

对我如何使这项工作有任何想法?

更新.除了子菜单之外,我对所有东西都有这个工作.我正在使用以下代码,该代码改编自该线程中的一个答案:

$(document).ready(function () {var listItems = $('.navbar ul li');$.each(listItems, function (key, litem) {var aElement = $(this).children(litem)[0];if(aElement == document.URL) {$(litem).addClass('active');}});});

我唯一缺少的是向子菜单项添加活动.这段代码正在获取 .navbar ul li 项的第一个子项并进行比较以查看是否需要添加活动类.我知道当我有一个 .nav-item .dropdown 类的 li 时,我需要遍历 .dropdown-menu 的子项,并在那里检查.我只是在努力弄清楚如何.我真的需要参加 JQuery 课程.

进一步

在玩了几个小时后,我有一个解决方案,适用于我正在尝试做的事情:

var setSubItemParent = false;$(document).ready(function () {var listItems = $('.navbar ul li');$.each(listItems, function(key, litem) {迭代链接(项目);})});函数迭代链接(liItem){var divchildren = $(liItem).children('div');setSubItemParent = false;/* 如果有 div 子级,迭代它们 */如果(divchildren.length > 0){iterateLinks(divchildren[0]);/* 如果设置了一个项目并且我们在一个 div 中,则将 active 添加到这个元素也是.*/如果(setSubItemParent){$(liItem).addClass('active');}}别的 {var achildren = $(liItem).children('a');/* 运行所有 a 标签,看看它们是否应该处于活动状态 */如果 (achildren.length > 0 ) {$.each(achildren, function(key, achild) {如果(achild.href == document.URL){$(achild).addClass('active');setSubItemParent = true;}});}}}

代码遍历菜单中的所有 li 元素,如果找到 div 则进一步挖掘.这可能不是解决问题的最强大的解决方案,但它确实有效.不过,我愿意接受更好的解决方案.

解决方案

您可以遍历链接并检查链接的 href 是否与文档 URL 匹配,然后将活动类添加到链接(或在 li).

$(document).ready(function () {const $links = $('.navbar ul li a');$.each($links, function (index, link) {if (link.href == document.URL) {$(this).addClass('active');}});});

Using Bootstrap 4 v6, I have the following navigation:

I'm trying to set the active class on the selected menu item, but nothing I've done has worked.

The closest that I've come is with this code:

$(document).ready(function() {
$('.navbar ul li').click(function(e) {
    $('.navbar ul li.active').removeClass('active');
    var $this = $(this);
    if (!$this.hasClass('active')) {
        $this.addClass('active');
    }
    e.preventDefault();
});
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">DCH</a>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item active">
                <a class="nav-link" href="index.php">Home</a>
            </li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Feline Diabetes</a>
                <div class="dropdown-menu bg-inverse navbar-inverse">
                    <a class="dropdown-item" href="treatment.php">Treatment</a>
                    <a class="dropdown-item" href="insulin.php">Insulin and Testing</a>
                    <a class="dropdown-item" href="relatedconditions.php">Related Conditions</a>
                </div>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="nutrition.php">Nutrition</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="protocol.php">Protocol</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="links.php">Links</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="http://diabeticcathelp.com/forum" target="_blank">Forum</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="contact.php">Contact Us</a>
            </li>
        </ul>
    </div>
</nav>

It does change the active class to the clicked menu item, but it does not change the pages. It also doesn't work on the submenu items, though I think that I would need different code to see if those particular items were clicked and I haven't gotten that far. First, I'd like to get past the page switching issue. If I remove the e.preventDefault() call, then the pages shift, but the menu items are not changed to active.

Any ideas on how I might make this work?

Update. I have this working for everything except for the submenus. I'm using the following code, which is adapted from one of the answers in this thread:

$(document).ready(function () {
    var listItems = $('.navbar ul li');

    $.each(listItems, function (key, litem) {
        var aElement = $(this).children(litem)[0];

        if(aElement == document.URL) {
            $(litem).addClass('active');
        }
    });
});

The only thing that I'm missing is the adding active to the submenu items. This code is taking the first child item of .navbar ul li items and doing the comparison to see if I need to add the active class. I know that when I have an li with a class of .nav-item .dropdown that I need to step through the children of the .dropdown-menu, and check there. I'm just struggling to figure out how. I really need to take a JQuery course.

Further edit:

After playing with this for a few hours, I have a solution that works for what I'm trying to do:

var setSubItemParent = false;

$(document).ready(function () {
    var listItems = $('.navbar ul li');

    $.each(listItems, function(key, litem) {
        iterateLinks(litem);
    })
});

function iterateLinks(liItem) {
    var divchildren = $(liItem).children('div');

    setSubItemParent = false;

    /* If there are div children, iterate them */
    if (divchildren.length > 0) {
        iterateLinks(divchildren[0]);

        /* If an item was set and we're in a div, add active to 
           this element as well. */
        if(setSubItemParent) {
            $(liItem).addClass('active');
        }

    }
    else {
        var achildren = $(liItem).children('a');

        /* Run through all a tags and see if they should be active */
        if (achildren.length > 0 ) {
            $.each(achildren, function(key, achild) {
                if (achild.href == document.URL) {
                    $(achild).addClass('active');
                    setSubItemParent = true;
                }
            });
        }
    }
}

The code runs through all of the li elements in the menu and digs further if it finds a div. This probably isn't the most robust solution to the problem, but it does work. I am open to a better solution, however.

解决方案

You can iterate over the links and check if the href of the link matches the document URL then add the active class to the link (or in the li).

$(document).ready(function () {
  const $links = $('.navbar ul li a');
  $.each($links, function (index, link) {
    if (link.href == document.URL) {
      $(this).addClass('active');
    }
  });
});

这篇关于将活动类添加到菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆