我在 mvc 中有一个项目,其中所有页面都有一个侧边栏,如下所示:
<ul class="nav nav-pills nav-stacked text-center" style="padding-right:2px;" >
<li>
<a href="#collapse1" id="btn-1" class="text-center" data-toggle="collapse"><span><b>A</b></span> </a>
<ul class="nav nav-pills nav-stacked text-center collapse " id="collapse1" role="menu" aria-labelledby="btn-1" aria-expanded="false">
<li><a href="~/A/A-a">A-a</a></li>
<li><a href="~/A/A-b">A-b</a></li>
<li><a href="~/A/A-c">A-c</a></li>
</ul>
</li>
<li>
<a href="#collapse2" class="text-center" data-toggle="collapse"><span><b>B</b></span></a>
<ul id="collapse2" class="collapse nav nav-pills nav-stacked text-center collapse" aria-expanded="false">
<li><a href="~/B/B-a">B-a</a></li>
<li><a href="~/B/B-b">B-b</a></li>
</ul>
</li>
</ul>
当用户点击一个链接时:
<li><a href="~/B/B-b">B-b</a></li>
它的视图(页面)显示在侧边栏旁边,但问题是因为刷新或重新加载页面,通过单击标签,子菜单折叠,我需要保持打开状态。
我在网上搜索了很多,有人建议使用 html5 的本地存储,但所有示例都与导航选项卡相关。
下面是一个关于如何保存和恢复 Bootstrap 导航菜单“展开”状态的示例。
要保存的数据是aria-expanded
每个ul
.
$(document).ready(function(){
//localStorage.clear(); // Uncomment to clear ALL storage.
// Timer needed because of Bootstrap's animation delay.
var timer;
$("ul").on("click",function(e){
console.log("Click!");
// Clear previous timer if any.
clearTimeout(timer);
timer = setTimeout(function(){
// Get expanded states for each ul.
var expanded=[];
$("ul").each(function(){
var thisExpanded = $(this).attr("aria-expanded");
console.log(thisExpanded);
if(typeof(thisExpanded) != "undefined"){
expanded.push( thisExpanded );
}else{
expanded.push("undefined");
}
});
// Show it in console.
var expandedString = JSON.stringify(expanded);
console.log( expandedString );
// Save it in Storage.
localStorage.setItem("ULexpanded",expandedString);
},600);
});
// On load, set ul to previous state.
console.log("---- On Load.");
// Parse the string back to an array.
var previousState = JSON.parse(localStorage.getItem("ULexpanded"));
console.log(previousState);
// If there is data in locaStorage.
if(previousState != null){
console.log("Setting ul states on...");
$("ul").each(function(index){
// If the ul was expanded.
if(previousState[index] == "true"){
console.log("Index #"+index);
$(this).addClass("show").attr("aria-expanded", previousState[index]);
}
});
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句