navbar active option does not remain active after loading page

让人想犯罪 __ 提交于 2021-02-05 11:33:18

问题


I have a navbar in my code. this is located in ejs file name nav.ejs

<nav class="navbar navbar-expand-sm bg-dark navbar-dark mr-auto" >
    
    <div class="collapse navbar-collapse" id="myNavbar">
        <ul class="nav navbar-nav   ">
            <li class="nav-item">
                <a class="nav-link  " href="#">link1</a>
            </li>

            <li class="nav-item">
                <a class="nav-link" href="#">link2</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">link3</a>
            </li>

        </ul>
    </div>
</nav>

every time that i click an item in navbar it should become active.I place this line of code to each page. so that by clicking its link in navbar it becomes active.

window.onload = function() {
    document.getElementById('about').classList.add('active');
}

window.onload = function() {
    document.getElementById('write').classList.add('active');
}

window.onload = function() {
    document.getElementById('home').classList.add('active');
};

I want that to move this line of code to a sample.js file. so in this case in a file I have this code together. by clicking each link, only that last line in executed:

document.getElementById('home').classList.add('active');

I try to write it using jquery:

$(window).on("load", function() {
   
    $('.nav-link ').click(function() {
        // event.preventDefault();
   
       $(this).addClass('active').siblings().removeClass('active');
         document.getElementById('about').classList.add('active');

      
    })
});

but it doesn't work.


回答1:


in Website whenever a page reloads its erase all previous setting which is made temporary(now your saving making your active tab for temporary), it means it doesn't save the things you have done in the page, to resolve this you need to use local storage, that keeps data of the active tab and whenever you reload the page that will assign the data it's kept. you can learn more about local storage in this .

hope this will give you some idea.



来源:https://stackoverflow.com/questions/62595116/navbar-active-option-does-not-remain-active-after-loading-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!