Toggle DIV state localstorage

我怕爱的太早我们不能终老 提交于 2019-12-24 02:44:19

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28215149/toggle-div-state-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!