How to use cookies or local-storage for add a clas

2019-07-17 05:44发布

问题:

I have 2 different pages with common sidebar menu. In my example, you can see Parent Menus with Submenus. In Dashboard I've page1 sub-menu, when I click on it, redirects to other pages, I want in sidebar Parent menu should add a class. Even I refresh the page.

Here is my HTML code

Check this fiddle

<ul class="nav nav-sidebar">
    <li class="sidebar-nav-item with-sub">
        <a href="" class="sidebar-nav-link"><i class="icon ion-ios-home-outline"></i> Dashboard</a>
        <ul class="nav sidebar-nav-sub">
            <li class="nav-sub-item"><a href="menu1.html" class="nav-sub-link">Page 01</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Page 02</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Page 03</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Page 04</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Page 05</a></li>
        </ul>
    </li>
    <li class="sidebar-nav-item with-sub">
        <a href="" class="sidebar-nav-link"><i class="icon ion-ios-home-outline"></i> Menu</a>
        <ul class="nav sidebar-nav-sub">
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Menu 01</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Menu 02</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Menu 03</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Menu 04</a></li>
            <li class="nav-sub-item"><a href="" class="nav-sub-link">Menu 05</a></li>
        </ul>
    </li>
    <li class="sidebar-nav-item with-sub">
        <a href="" class="sidebar-nav-link"><i class="icon ion-ios-book-outline"></i> Pages</a>
        <ul class="nav sidebar-nav-sub">

            <li class="nav-sub-item sub-with-sub">
                <a href="#" class="nav-sub-link">Pricing</a>
                <ul>
                    <li class="sub-sub-link"><a href="">Pricing 01</a></li>
                    <li class="sub-sub-link"><a href="">Pricing 02</a></li>
                    <li class="sub-sub-link"><a href="">Pricing 03</a></li>
                </ul>
            </li>

        </ul>
    </li>
</ul>

回答1:

Since you're using jQuery, you could use the jquery lib js-cookie to add the selected menu to the cookies then read it in the other pages and attach the class.

But I suggest another way based on the URL of the page target the related anchor them activate the parent sidebar menu item.

Add the following line to the top of your ready function :

$(document).ready(function() {
    $('a[href="'+window.location.pathname+'"]').closest('.sidebar-nav-item').find('.sidebar-nav-link').addClass('active');

    ...
});