jQuery和HTML,如何在下拉切换菜单中使用本地存储

我有一个问题问你。我正在尝试在下拉切换菜单中使用localstorage。我有以下HTML代码:

<li class="nav-item" id="sidebar">
                    <a class="sidebar-heading" href="#thirdSubmenu" data-toggle="collapse" 
                    class="dropdown-toggle">Anagrafica</a>
                    <ul class="collapse list-unstyled" id="thirdSubmenu">
                        <li>
                            <a class="nav-link" href="">
                                <span data-feather="database"></span>
                                Categorie Materiale</a>
                        </li>
                        <li>
                            <a class="nav-link" href="">
                                <span data-feather="database"></span>
                                Sottocategorie Materiale</a>
                        </li>

..

我想要这样,当我单击Anagrafica并打开下拉菜单时,当我更新页面时它也保持打开状态,存储是否打开了dropdwon。我已经尝试了以下代码,但是可以正常工作。我不擅长jQuery,所以希望你们中的某人可以帮助我。

这是我的jQuery代码:

    $("#thirdSubmenu li a").on("click", function() {
    var container = $(this).closest("li");
    var selected_item_index = $("#thirdSubmenu li a").index(container);
    localStorage.setItem("sidebar_selected", selected_item_index );
});

$(function() {
    $("#thirdSubmenu li").eq(parseInt(localStorage.getItem("selected_item_index "))).addClass("active");
});
评论
念念不忘
念念不忘

You want to index the parent <li> within it's siblings

尝试改变

 $("#thirdSubmenu li a").on("click", function() {
    var container = $(this).closest("li");
    var selected_item_index = $("#thirdSubmenu li a").index(container);
    localStorage.setItem("sidebar_selected", selected_item_index );
});

 $("#thirdSubmenu li a").on("click", function() { 
    // get index of parent `<li>` within it's siblings       
    var selected_item_index = $(this).parent().index();
    localStorage.setItem("sidebar_selected", selected_item_index );
});
点赞
评论