简体   繁体   English

从Javascript对象循环动态创建的表单。 如何将数据保存回对象

[英]Form created dynamically from Javascript Object loop. How to save data back to object

I have the following code that takes in a string a modifies it into an object. 我有以下代码,将一个字符串a修改为一个对象。 I then create a list of items and when the user clicks on one of the list items it creates a form with the values that were in the object assigned to that key. 然后,我创建一个项目列表,当用户单击其中一个列表项目时,它将创建一个表单,该表单具有分配给该键的对象中的值。

The problem I am having is editing the form data and saving it back to the object since the form was created dynamically. 由于表单是动态创建的,所以我遇到的问题是编辑表单数据并将其保存回对象。

Demo: http://jsfiddle.net/kHysL/1/ 演示: http//jsfiddle.net/kHysL/1/

code(dont pay any attention to the code above $(document).ready()... Its the string parser) : 代码(不要注意$(document).ready()上面的代码。它是字符串解析器):

var str = 'View\n{\n    Name: View1;\n    Image\n    {\n        BackgroundImage: Image.gif;\n        Position: 0, 0;\n        Width: 320;\n        Height: 480;\n    }\n\n    Button\n    {\n        BackgroundImage: Button.gif;\n        Transition: View2;\n        Position: 49, 80;\n        Width: 216;\n        Height: 71;\n    }\n\n    Button\n    {\n        BackgroundImage: Button2.gif;\n        Position: 65, 217;\n        Width: 188;\n        Height: 134;\n    }\n\n    Label\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Text: "Button";\n        FontSize: 32;\n        Color: 0.12549, 0.298039, 0.364706, 1;\n    }\n    Scroll\n    {\n        Position: 106, 91;\n        Width: 96;\n        Height: 34;\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n            Height: 134;\n        }\n        Button{\n            BackgroundImage: Button2.gif;\n            Position: 65, 217;\n            Width: 188;\n     \n      Height: 134;\n        }\n\n    }\n\n}';

str = str.replace(/(\w+)\s*\{/g, "$1:{"); // add in colon after each named object
str = str.replace(/\}(\s*\w)/g, "},$1"); // add comma before each new named object
str = str.replace(/;/g, ","); // swap out semicolons with commas
str = str.replace(/,(\s+\})/g, "$1"); // get rid of trailing commas
str = str.replace(/([\d\.]+(, [\d\.]+)+)/g, "[$1]"); // create number arrays
str = str.replace(/"/g, ""); // get rid of all double quotes
str = str.replace(/:\s+([^\[\d\{][^,]+)/g, ':"$1"');  // create strings

$("#parseList").html(str);

var objStr;
eval("objStr={" + str + "};");

//End Parse String

$(document).ready(function () {
    var selected;
    //Build Initial Object LIst
    var initObjectList = '<div id="main">';
    $.each(objStr.View, function (k, v) {
        initObjectList += '<div>' + k + '</div>';

    });
    initObjectList += '</div>';
    $('#main').append(initObjectList)

    $(document).on('click', '#main div div', function () {
        var index = $('#main div div').index(this);

        $(this).click(function () {
            $('#form div').remove();
            codeSnippet = "";
            x = $('#main div div').toArray();
            codeSnippet = (x[index].innerHTML);
            console.log(codeSnippet);

            var initObjectDetail = '<div id="form">';
            $.each(objStr.View[codeSnippet], function (k, v) {
                initObjectDetail += '<div>' + k + '</div>' + '<input value=' + v + '>' + '</input>';
                console.log(v);

            });
            initObjectList += '</div>';
            $('#form').append(initObjectDetail)
        });

    });
});​

Input of how to save it back to the object would be appreciated 输入如何将其保存回对象将不胜感激

Making the clickable object list can be greatly simplified by specifying the click handler inside the original loop that forms the list. 通过在形成列表的原始循环内指定单击处理程序,可以大大简化制作可单击对象的列表。

Form generation and Save functionality are complicated by a quirk of the data, namely that one of the objStr.View properties is a string while the other properties are objects. 表单生成和保存功能由于数据的怪异而变得复杂,即objStr.View属性之一是字符串,而其他属性是对象。 You will see below that we have to branch in two places to handle this difference. 您将在下面看到我们必须在两个地方分支以解决这种差异。

$(document).ready(function () {
    var $objectList = $('<div id="main" />').appendTo($('#main'));
    $.each(objStr.View, function(k, v) {
        $('<div/>').append(k).appendTo($objectList).on('click', function(){
            var $wrapper = $('#form .wrapper').empty();
            if(typeof v === 'string') {
                $('<div class="item" />').append('<span class="key">' + k + '</span>' + '<input value="' + v + '"/>').appendTo($wrapper);
            }
            else {//object
                $('<h3 class="formHeading" />').append(k).appendTo($wrapper);
                $.each(v, function(key, val) {
                    $('<div class="item" />').append('<span class="key">' + key + '</span>' + '<input value="' + val + '"/>').appendTo($wrapper);
                });
            }
            $("<button>Save</button>").appendTo($wrapper).on('click', function() {
                if(typeof v === 'string') {
                    v = $(this).closest(".wrapper").find("input").val();
                }
                else {//object
                    $(this).closest(".wrapper").find(".item").each(function(i, div) {
                        var $div = $(div),
                            key = $div.find(".key").text(),
                            val = $div.find("input").val();
                        v[key] = val;
                    });
                }
            });
        });
    });
});

You will also see that this code doesn't need a "Save" button hard coded in the HTML. 您还将看到此代码不需要在HTML中硬编码的“保存”按钮。 A new "Save" button is generated each time the form is populated. 每次填充表单时都会生成一个新的“保存”按钮。 It doesn't have to be this way, but that's the approach I adopted. 不一定要这样,但这就是我采用的方法。

Updated fiddle 更新的小提琴

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

相关问题 从json动态创建的Javascript表单输入,需要将对象映射到另一个对象的适当字段并保存 - Javascript form inputs created dynamically from json and need to map object to proper field from another object and save Javascript不等待For循环。 对象值不变 - Javascript not waiting for For loop. Object values not changing 如何从动态创建的输入表单为IndexedDB创建合适的对象 - How to create a suitable object for IndexedDB from a dynamically created input form 动态创建的javascript对象 - dynamically created javascript object 如何使用JQuery或javascript从动态创建的按钮获取单击事件对象数据 - How to get click event object data from dynamically created button using JQuery or javascript 如何使用 javascript for 循环创建新数组。 我收到错误“圆形对象对象” - How do I create a new array with a javascript for loop. I got the error "circular object Object" 从JavaScript循环创建的对象,如何在json中分析它们 - Object created from a loop in JavaScript, how to analyse them in a json 如何在Javascript中将数据保存在对象中 - How to save data in object in Javascript 如何保存使用JavaScript动态创建的HTML表单 - How to save html form created dynamically using javascript JavaScript动态创建的对象未定义 - JavaScript Dynamically created object undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM