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

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

问题描述

使用Bootstrap 4 v6,我可以进行以下导航:

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>

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

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');
        }
    });
});

我唯一缺少的是将活动添加到子菜单项.这段代码接收.navbar ul li项目的第一个子项目,并进行比较以查看是否需要添加活动类.我知道当我有一个带.nav-item .dropdown类的li时,我需要逐步浏览.dropdown菜单的子项并进行检查.我只是在努力想办法.我真的需要参加JQuery课程.

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.

进一步

在玩了几个小时之后,我有了一个可以解决我想要做的事情的解决方案:

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;
                }
            });
        }
    }
}

代码遍历菜单中的所有li元素,如果找到div,则进一步挖掘.这可能不是解决该问题的最可靠的方法,但是它确实起作用.但是,我愿意寻求更好的解决方案.

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.

推荐答案

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

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天全站免登陆