我有以下代码,它接受一个字符串 a 将其修改为一个对象。然后我创建一个项目列表,当用户单击其中一个列表项目时,它会创建一个表单,其中包含分配给该键的对象中的值。
我遇到的问题是编辑表单数据并将其保存回对象,因为表单是动态创建的。
演示:http: //jsfiddle.net/kHysL/1/
代码(不要注意上面的代码 $(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)
});
});
});
输入如何将其保存回对象将不胜感激