问题
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