如何使用保存的html从Gridstack构建网格

时间:2015-05-21 16:17:47

标签: javascript jquery grid

我一直在使用Gridstack来动态创建网格。我使用了以下函数来序列化网格及其数据。但我似乎无法弄清楚如何从它创建的JSON数组构建我的网格其内容。我已经检查了https://github.com/troolee/gridstack.js#load-grid-from-array,但添加内容部分是整个问题。

function saveData() {
        var s_data = [];

        $('.grid-stack-item.ui-draggable').each(function () {
            var $this = $(this);

            s_data.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()
            });
        });         
    }

这会创建以下数组:

[
    {"x":"0","y":"0","w":"4","h":"2","content":"<h1>Test title for content</h1>"},
    {"x":"4","y":"0","w":"4","h":"4","content":""}
];

所以我的问题是:如何使用这个数组构建我的网格,包括其内容?

1 个答案:

答案 0 :(得分:6)

我回答了类似的问题here

在您的情况下,您可以在gridstack序列化示例提供的加载函数中使用以下代码:

this.load_grid = function () {              

    var items = GridStackUI.Utils.sort( this.s_data );
    this.grid.remove_all();

    _.each( items, function( node ) {
        this.grid.add_widget( jQuery( '<div class="grid-stack-item"><div class="grid-stack-item-content">' + node.content + '</div></div>' ), node.x, node.y, node.width, node.height );
    }, this );

}.bind( this );