简体   繁体   English

无法从浏览器存储加载布局内容

[英]Unable to load layout content from browser storage

I am using a library called gridstack.js .我正在使用一个名为gridstack.jslibrary I have a grid which looks like below ↓我有一个如下所示的grid

图片

This is the code I used:这是我使用的代码:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gridstack@2.0.0/dist/gridstack.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
<script src="https://cdn.jsdelivr.net/npm/gridstack@2.0.0/dist/gridstack.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

<style>

.card-body {
    -webkit-box-flex: 1;
    -ms-flex: 1 1 auto;
    flex: 1 1 auto;
    min-height: 1px;
    padding: 1.25rem;
}

.newWidget {
    background-color: #6cad84 !important;
}
.card {
    background: none;
}

#trash {
    background-color: #cc6857;
}
.text-white {
    color: #fff !important;
}
.text-center {
    text-align: center !important;
}

    
.ui-resizable-se, .ui-resizable-sw {
    opacity: 0 !important;
}

.ui-resizable-se {
    bottom: -5px !important;
    right: -5px !important;
}


.grid-stack-item-content{
    overflow:hidden !important
}

    

</style>


<body>


<div class="container-fluid">
    <span id="dashboardName">
        <p>My dashboard</p>
    </span>

    <div class="row">


        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 "> 

            <!-- gridstack.js elements go here -->
            <div class="grid-stack">
               

             <div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="3" data-gs-width="7" data-gs-height="4">
                    <div class="grid-stack-item-content ui-draggable-handle card-color card-body cardProperty">
                        <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">

                    </div>
              </div>


              <div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="8" data-gs-y="6" data-gs-width="5" data-gs-height="4">
              
                <div class="grid-stack-item-content ui-draggable-handle  panel-warning  card-body cardProperty">
                            
                            <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">
                </div>
            </div>

             


              <div class="grid-stack-item ui-draggable-handle ui-resizable" data-gs-x="0" data-gs-y="6" data-gs-width="4" data-gs-height="4">
                    
                    <div class="grid-stack-item-content card-body ui-draggable-handle card-color cardProperty">
                        
                        <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80">

                    </div>
             </div>


             <div class="grid-stack-item ui-draggable-handle ui-resizable hasPanelHeader " data-gs-x="4" data-gs-y="6" data-gs-width="4" data-gs-height="4">
              
                <div class="grid-stack-item-content ui-draggable-handle  panel-warning  card-body cardProperty">
                            
                            <img src="https://images.unsplash.com/photo-1541890289-b86df5bafd81?ixlib=rb-1.2.1&w=1000&q=80"> 
                </div>
            </div>

            </div>

        </div>

     </div> 
</div>


<script type="text/javascript">

// save the size and coordinates of the widgets
function saveData() {
    var items = [];

    $('.grid-stack-item.ui-draggable').each(function () {
        var $this = $(this);
        items.push({
            x: $this.attr('data-gs-x'),
            y: $this.attr('data-gs-y'),
            w: $this.attr('data-gs-width'),
            h: $this.attr('data-gs-height'),
            content: $('.grid-stack-item-content', $this).html()
        });
    });

    // Save data to local storage
    localStorage.setItem("grid-layout", JSON.stringify(items))
}


// check for widgets size and coordinates and add to the grid
function getWidgetData() {

    let serialization = null;
    let grid_stack = $('.grid-stack');
    let grid = $('.grid-stack').data('gridstack')
    console.log("grid", grid)

    if (localStorage.getItem("grid-layout") !== null) {

        serialization = JSON.parse(localStorage.getItem("grid-layout"));

        _.each(JSON.parse(serialization), function (node) {
            grid.addWidget($('<div><div class="grid-stack-item-content"> </div></div>'),
                node.x, node.y, node.w, node.h);
        });

       
    } else {
        console.log("There was no local storage data to read")
    }
}


// check for localstorage in the beginning
getWidgetData ()

var simpleGrid = GridStack.init({
      alwaysShowResizeHandle: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator
        .userAgent),
      resizable: {
        handles: 'e, se, s, sw, w, n'
      },
      animate: true,
      acceptWidgets: true,
      dragIn: '.newWidget',  // class that can be dragged from outside
      dragInOptions: { revert: 'invalid', scroll: false, appendTo: 'body', helper: 'clone' },
      removable: '#trash', // drag-out delete class
      removeTimeout: 100,
});

// save the widgets layout on every change
simpleGrid.on('added removed change', function(e, items) {
    saveData()
});

</script>

</body>

Now the grid appears fine and I am able to resize and drag the widgets .现在grid看起来很好,我可以resizedrag widgets Now I want to store the changes in my browser storage and retrieve it on page load.现在我想store更改存储在浏览器存储中并在页面加载时检索它。 So as mentioned in the code above, this is what I do to store the layout所以正如上面代码中提到的,这就是我用来store布局的

// save the size and coordinates of the widgets
function saveData() {
    var items = [];

    $('.grid-stack-item.ui-draggable').each(function () {
        var $this = $(this);
        items.push({
            x: $this.attr('data-gs-x'),
            y: $this.attr('data-gs-y'),
            w: $this.attr('data-gs-width'),
            h: $this.attr('data-gs-height'),
            content: $('.grid-stack-item-content', $this).html()
        });
    });

    // Save data to local storage
    localStorage.setItem("grid-layout", JSON.stringify(items))
}

Now to load the layout from browser storage, this is what I do (mentioned in the code above)现在从浏览器存储load布局,这就是我所做的(在上面的代码中提到)

// check for widgets size and coordinates and add to the grid
function getWidgetData() {

    let serialization = null;
    let grid_stack = $('.grid-stack');
    let grid = $('.grid-stack').data('gridstack')
    console.log("grid", grid)

    if (localStorage.getItem("grid-layout") !== null) {

        serialization = JSON.parse(localStorage.getItem("grid-layout"));

        _.each(JSON.parse(serialization), function (node) {
            grid.addWidget($('<div><div class="grid-stack-item-content"> </div></div>'),
                node.x, node.y, node.w, node.h);
        });


    } else {
        console.log("There was no local storage data to read")
    }
}

But for some reason I get this error但由于某种原因,我收到此错误

index.html:156 Uncaught TypeError: Cannot read property 'addWidget' of undefined
    at index.html:156
    at r (lodash.min.js:9)
    at Function.hf (lodash.min.js:83)
    at getWidgetData (index.html:155)
    at index.html:168

Turns out this piece of code below原来是下面这段代码

 let grid = $('.grid-stack').data('gridstack')

It gives undefined for some reason.由于某种原因,它给出了undefined Now I just can't figure out why it is undefined.现在我无法弄清楚为什么它是未定义的。 I looked up online for help but didn't find anything useful that solves my problem.我在网上寻找帮助,但没有找到任何有用的东西来解决我的问题。 I found these two questions on stack overflow我在堆栈溢出上发现了这两个问题

Gridstack undefined when calling $(".grid-stack").data("gridstack") in global context 在全局上下文中调用 $(".grid-stack").data("gridstack") 时未定义 Gridstack

can't read property addWidget of undefined with JSON and gridstack 无法使用 JSON 和 gridstack 读取未定义的属性 addWidget

But I don't quite understand what they are doing or if it applies in my case.但我不太明白他们在做什么,或者它是否适用于我的情况。 What am I doing wrong?我究竟做错了什么?

as mentioned in the 'bug' reported https://github.com/gridstack/gridstack.js/issues/1405 , he's mixing old API call of $(".grid-stack") which is jquery code based for v0.6 and older and the latest version 2.x which uses GridStack.init() to init and return a grid pointer.正如在https://github.com/gridstack/gridstack.js/issues/1405报告的“错误”中提到的,他混合了$(".grid-stack")的旧 API 调用,这是基于 v0.6 的 jquery 代码以及使用GridStack.init()初始化并返回网格指针的较旧和最新版本GridStack.init()

GridStack does not use jquery API since 1.x GridStack 自 1.x 起不再使用 jquery API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Cloud Storage - 如何直接从浏览器上传内容 (JavaScript) - Google Cloud Storage - How to Upload content directly from browser (JavaScript) 无法将内容从 JS 加载到 HTML - Unable to Load Content from JS to HTML 无法从 content.js 文件向浏览器注入代码 - Unable to inject code to the browser from the content.js file 无法在浏览器上显示内容-AngularJS - Unable to display content on browser -AngularJS 无法从另一台服务器加载脚本-内容安全策略问题? - Unable to load script from another server - Content Security Policy issue? 如何从服务器加载我的网站而不在浏览器控制台中进行干净存储? - how to get load my site from server without clean storage in browser console? 无法使用 Rest API (JavaScript) 从浏览器上传 Azure 存储文件共享文件 - Unable to upload Azure Storage File Share File from browser using Rest API (JavaScript) 每次页面加载时自动将本地存储数据从chrome扩展名传递到内容脚本 - Passing local storage data from chrome extension to content script automatically on every page load 无法使用 javascript 从本地存储中加载已保存的 position - Unable to load saved position of dropped item from local storage using javascript 即使呈现所有内容,浏览器也会尝试加载 - Browser tries to load even if all the content are rendered
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM