如何使用页面重新加载时打开和关闭状态的唯一id修改引导折叠

How to Modify Bootstrap Collapse with a unique id for open and closed state on page reload

本文关键字:状态 唯一 id 折叠 修改 何使用 新加载 加载      更新时间:2023-09-26

我使用bootstrap collapse构建了一个扩展的树列表。(没有手风琴,这似乎是罕见的,我在尝试谷歌时学会了)我遇到的第一个问题是,每个项目在页面重新加载上的打开/关闭位置,没有记录,因此需要使用本地存储保存。容易。

然而,接下来的问题是让每个树项单独行动,而不记住彼此的位置。因此,我们需要为的每个单独的项的打开和关闭状态生成一个唯一的ID,以便它们不会同时打开和关闭。

更新:

感谢SPViradiya提供了这个简单的解决方案,结合了开放,关闭和旋转箭头,与很少的HTML和CSS。

https://jsfiddle.net/SPViradiya/nm6tqxsL/1/

$(document).ready(function () {
    var getUniqueID = localStorage.getItem('uniqueid');
if( typeof getUniqueID == "string" )
{
    var parsedUID = JSON.parse(getUniqueID);
  if( parsedUID != "" && typeof parsedUID == "object" )
  {
    for( item in parsedUID )
    {
        if(parsedUID[item])
        {
         $( "#"+item).collapse('show');
         console.log($( "div[href='#"+item+"']"));
         $( "div[href='#"+item+"']").addClass('rotateOn');
        }
        else
        {
         $( "#"+item).collapse('hide');
         $( "div[href='#"+item+"']").removeClass('rotateOn');
        }
    }
  }
}
$('.expand').click(function() {
    //store the id of the collapsible element
     $(this).toggleClass('rotateOn');
   setTimeout(function(){
    var uniqueid = {};
    $('.expand').each(function(){
       var getID = $(this).attr('href').replace(/#/g,'');
       uniqueid[getID] = $("#"+getID).hasClass('in');
    }); 
    localStorage.setItem('uniqueid', JSON.stringify(uniqueid)); 
   },500);

});
})

要生成唯一的id,请使用Date.now()并将返回值附加到给定的字符串,如:

var id = "id-" + Date.now(); // id-1477557085096

Date.now()方法返回自UTC时间1970年1月1日00:00:00以来经过的毫秒数。

试试下面的代码

var getUniqueID = localStorage.getItem('uniqueid');
if( typeof getUniqueID == "string" )
{
    var parsedUID = JSON.parse(getUniqueID);
  if( parsedUID != "" && typeof parsedUID == "object" )
  {
    for( item in parsedUID )
    {
        if(parsedUID[item])
         $( "#"+item+).collapse('show');
        else
         $( "#"+item+).collapse('hide');
    }
  }
}
$('.expand').click(function() {
    //store the id of the collapsible element
    var uniqueid = {};
    $('.expand').each(function(){
       var getID = $(this).attr('href').replace(/#/g,'');
       uniqueid[getID] = $(this).hasClass('collapsed');
    }); 
    localStorage.setItem('uniqueid', JSON.stringify(uniqueid)); 

});