dongzhiyong8577 2015-07-10 11:27
浏览 59

将html存储在json文件中并使用Jquery循环它

This is my code:

$(document).ready(function () {

    $.getJSON("data.json", function(data) {
        if (data!=null) {  
            response = JSON.parse(data)
            $.each(response, function(i,value) {       
                var id_name;id_name="#";   
                id_name = id_name + value.id;       
                $(id_name).attr({"data-col":value.col, "data-row":value.row, "data-sizex":value.size_x, "data-sizey":value.size_y});
            });
        } else {   
            console.log('No data returned by the server. Continue with the default positions');   
        }
    });

    // widget_selector: "> ul"
    // Define which elements are the widgets. Can be a CSS Selector string or a jQuery collection of HTMLElements.

    // widget_margins: [3, 3]
    // Horizontal and vertical margins respectively for widgets.

    // widget_base_dimensions: [110, 110]
    // Base widget dimensions in pixels. The first index is the width, the second is the height.

    var grid_canvas = $(".gridster > ul").gridster({
        widget_margins: [3, 3],
        widget_base_dimensions: [150, 150],

        // serialize_params: function($w, wgd) { return { id: $($w).attr('id'),col: wgd.col, row: wgd.row,size_x: wgd.size_x,size_y: wgd.size_y }
        // A function to return serialized data for each each widget, used when calling the serialize method. Two arguments are passed: 
        // $w: the jQuery wrapped HTMLElement which is used to get the id, and wgd: the grid coords object with keys col, row, size_x and size_y.

        serialize_params: function($w, wgd) 
        {
            return {
                id: $($w).attr('id'),
                col: wgd.col, 
                row: wgd.row,
                size_x: wgd.size_x,
                size_y: wgd.size_y,
            };
        },

        // draggable.stop: function(event, ui){} -- A callback for when dragging stops.
        // You can also implement other draggable options based on your requirements
        // draggable.start: function(event, ui){} -- A callback for when dragging starts.
        // draggable.drag: function(event, ui){} -- A callback for when the mouse is moved during the dragging. 

        draggable: {
            stop: function(event, ui) {
                // .serialize( )
                // Creates an array of objects representing the current position of all widgets in the grid.
                // Returns an Array of Objects (ready to be encoded as a JSON string) with the data specified by the serialize_params option
                // JSON.stringify() converts a primitive value, object or array to a JSON-formatted string that can later be parsed with JSON.parse().

                var positions = JSON.stringify(this.serialize());

                // With HTML5, web pages can store data locally within the user's browser.
                // Earlier, this was done with cookies. However, Web Storage is more secure and faster. 
                // The data is not included with every server request, but used ONLY when asked for. 
                // It is also possible to store large amounts of data, without affecting the website's performance.
                // The data is stored in key/value pairs, and a web page can only access data stored by itself.

                localStorage.setItem('positions', positions);

                $.post(
                    "process.php",
                    {"positions": positions},
                    function(data) {
                        // this is where you can check if your data is sent to the server or not.
                        // A status of 200 implies success

                        console.log(data);
                        if (data==200)
                            console.log("Data successfully sent to the server");
                        else
                            console.log("Failed")
                    }
                );

            }
        }   
    }).data('gridster');

    $('.1x-add').on('click', function() {
        grid_canvas.add_widget('<li class="new">...</li>', 1, 1);
    });
    $('.2x-add').on('click', function() {
        grid_canvas.add_widget('<li class="new">...</li>', 2, 1);console.log($(".gridster > ul").html())
    });

    //Predefined colorscheme, right now static but should be imported from the users choice. Loops through all boxes and randoms a color out of the array.
    $('ul li').each(function () {
        var back = ["#475f7b;","#75879c","#a3afbd"];
        var rand = back[Math.floor(Math.random() * back.length)];
        $(this).css('background',rand);
    });
})

Currently I am saving positions of the elements in a json file, as this:

[
    {\"col\":1,\"row\":1,\"size_x\":1,\"size_y\":1},
    {\"col\":1,\"row\":2,\"size_x\":2,\"size_y\":1},
    {\"col\":4,\"row\":1,\"size_x\":2,\"size_y\":1}
]

However.. This is only the positions of the hardcoded elements, I have a new function:

$('.1x-add').on('click', function() {
    grid_canvas.add_widget('<li class="new">...</li>', 1, 1);
});

This adds a new widget correctly, but I want to be able to save the full elements into the json file including the position. like:

[
    {<li id="1" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="2" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>},
    {<li id="3" data-row="2" data-col="1" data-sizex="1" data-sizey="1"></li>}
] 

and then loop them out from the json file.

Could anyone help me get on the road?

Or keep the position json at it is, and then just store the elements in another json file

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 python天天向上类似问题,但没有清零
    • ¥30 3天&7天&&15天&销量如何统计同一行
    • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
    • ¥15 C#调用python代码(python带有库)
    • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
    • ¥15 活动选择题。最多可以参加几个项目?
    • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
    • ¥15 vs2019中数据导出问题
    • ¥20 云服务Linux系统TCP-MSS值修改?
    • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)