简体   繁体   中英

How to set active class on current nav item

I am facing problem while setting active class on nav item. Here is my code on template

<nav class="mt-2">
        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
          <li class="nav-item">
            <a href="{{ url('/dashboard') }}" class="nav-link">
              <i class="nav-icon fas fa-tachometer-alt"></i>
              <p>
                Dashboard
              </p>
            </a>
          </li>
          <li class="nav-item">
            <a href="{{ url('/dashboard/logo') }}" class="nav-link">
              <i class="nav-icon fab fa-bandcamp"></i>
              <p>
                Add/Change Logo
              </p>
            </a>
          </li>
          
          <li class="nav-item has-treeview">
            <a href="#" class="nav-link">
              <i class="nav-icon fas fa-image"></i>
              <p>
                Banner
                <i class="fas fa-angle-left right"></i>
              </p>
            </a>
            <ul class="nav nav-treeview">
              <li class="nav-item">
                <a href="{{ url('/dashboard/banner') }}" class="nav-link">
                  <i class="nav-icon fas fa-plus"></i>
                  <p>Add Banner</p>
                </a>
              </li>
              <li class="nav-item">
                <a href="{{url('/dashboard/banner/edit')}}" class="nav-link">
                  <i class="nav-icon fas fa-edit"></i>
                  <p>Edit Banner</p>
                </a>
              </li>
            </ul>
          </li>

        </ul>
      </nav>

I tried

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  $(document).ready(function () {
        var url = window.location;
        $('ul.nav li.nav-item a[href="' + url + '"]').parent().addClass('active');
        $('ul.nav li.nav-item a').filter(function () {
            return this.href == url;
        }).parent().addClass('active').parent().parent().addClass('active');
  });
</script>

But this code setting the "active" class on list tag but not in anchor tag.

你可以看到这个检查元素截图

Instead of using .parent() , try using .closest('a') .

closest() will traverse UP the DOM tree until it finds the specified selector - in the above example, the first <a> tag above the element.

Virtually all of your .parent() can be replaced with .closest() - but use as desired. There is no "right" or "wrong", just what works or is easiest for you.

You can use any normal css/jQuery selector with closest() - from a tagName:

.closest('a')

to a className:

.closest('a.nav-item')

etc.

Reference:

https://api.jquery.com/closest/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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