这是一个侧边栏菜单,到目前为止,每次我重新加载页面时它都会关闭选项卡,这很烦人,我应该添加些什么来解决此问题?
_menu.html.erb
<div id="mySidepanel" class="sidepanel">
<button class="closebtn" onclick="closeNav()"><i class="fas fa-times-circle"></i></button>
<div class="dropdown-container">
<%= link_to "Journal", "#", class: "drop-item" %>
<%= link_to "Stats","#", class: "drop-item" %>
</div>
<li class="dropdown-btn">Suppliers
<i class="fa fa-caret-down"></i>
</li>
<div class="dropdown-container">
<%= link_to "Add a supplier", "#", class: "drop-item" %>
<%= link_to "Suppliers", "#", class: "drop-item" %>
</div>
<%= link_to "Orders", "#", class: "list-item" %>
<%= link_to "Users", "#", class: "list-item" %>
</div>
sidebar.js
编辑,添加了整个代码,我没有使用Bootstrap下拉列表
$(document).on('turbolinks:load', function() {
if ($('.dropdown-btn')){
activeTab = document.getElementsByClassName('active')[0].dataset.activeDropdown.myArticles
sessionStorage.setItem('foo', activeTab);
}
if(activeTab){
$('#mySidepanel a[href="' + activeTab + '"]').tab('show');
}
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
});
function openNav() {
document.getElementById("mySidepanel").style.width = "180px";
}
function closeNav() {
document.getElementById("mySidepanel").style.width = "0";
}
我添加了此js代码,但需要帮助:
$('.drop-item').on('shown.bs.tab', function (e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#mySidepanel a[href="' + activeTab + '"]').tab('show');
}
答案 0 :(得分:1)
您必须使用sessionStorage(我认为会话存储足以满足您的需求)。
在选项卡上进行更改时,存储选项卡的值(例如,他的ID):
localStorage.setItem('tabId', 'foo');
然后,在页面加载时,如果您的密钥存在,请打开选项卡。使用jQuery,应该是这样的:
$(function(){
if (localStorage.getItem('tabId') !== null) {
document.getElementById(localStorage.getItem('tabId')).show();
}
}
给您一个想法。它不是更干净。例如,您应该重写openNav
函数以接受参数(localStorage值)