Toggle DIV state localstorage

2019-07-21 10:49发布

Earlier today i asked a question on here, but didnt explained it properly and havent provided proper code.

I have 2 toggle DIVs with links in them, and once user opens one and clicks on the link, page refresh with results, but that DIV closes itself. I would like it to remain open.

$(document).ready(function() {
            $(".content").hide();
            $(".fa-angle-double-up").hide();
            $(".heading").click(function(){
                    $(this).next(".content").slideToggle(500);
                    $(this).find(".fa-angle-double-up, .fa-angle-double-down").toggle();
            });
        });

Somebody told me that it can be done either by setting cookies or by storing it into localstorage, but i have no idea (JS newbie).If anybody can help, you would save my day :)

Fiddle: http://jsfiddle.net/eg7ju4rm/

Moderators, if it is against the rules to post 2 questions with the same topic, i apologize

2条回答
beautiful°
2楼-- · 2019-07-21 11:02

In your click-event you can add this:

var id = $(this).parent().attr('id');
window.localStorage.setItem('opened', id);

to save the ID of the opened section. And add this to your ready-handler:

var opened =  window.localStorage.getItem('opened');
if(opened !== ''){
    $('#' + opened).find('.content').show();
}

Demo

I don't know if only one div should be stay open or every opend div, my solutions just handle one open div.

查看更多
虎瘦雄心在
3楼-- · 2019-07-21 11:26

You can indeed store references to the expanded elements in the localStorage (or perhaps sessionStorage could be more appropriate), and upon page load, restore their state:

$(document).ready(function() {
    var openTabs = [];

    $(".content").hide();
    $(".fa-angle-double-up").hide();

    $(".heading").click(function(){
        var $this = $(this),
        selector = '#' + $this.parent().attr('id') + ' .heading';

        if ($(this).next('.content').is(':visible'))
        {
            var pos = openTabs.indexOf(selector);
            openTabs.splice(pos, 1);
        }
        else
            openTabs.push(selector);

        localStorage.openTabs = openTabs.join(',');

        $this.next(".content")
             .slideToggle(500)
             .find(".fa-angle-double-up, .fa-angle-double-down")
             .toggle();
    });

    if (localStorage.openTabs)
        $(localStorage.openTabs).click();
});

Fiddle

Also, see DOM Storage

查看更多
登录 后发表回答