json字符串的拼接,并转换为json对象
<html> <head> <script> var qianzhui = "cc"; var test1=""; function test(){ var test="<table>"; for(var i=0;i<4;i++){ test = test + "<tr><td><input id='" + qianzhui + "_" + i + "1" + "'></input></td><td><input id='" + qianzhui + "_" + i + "2" + "'></input></td><td><input id='" + qianzhui + "_" + i + "3" + "'></input></td></tr>";//使用for循环向dom中写入表格内容 } test=test+"</table>"; document.getElementById("test").innerHTML = test; } function getTestValue() { test1="{"; for (var i = 0; i < 4; i++) { test1 = test1 + "\"cc" + i + "1\":" + "\"" + document.getElementById("cc_" + i + "1").value.toString().trim() + "\"," + "\"cc" + i + "2\":" + "\"" + document.getElementById("cc_" + i + "2").value.toString().trim() + "\"," + "\"cc" + i + "3\":" + "\"" + document.getElementById("cc_" + i + "3").value.toString().trim() + "\"";//使用for循环获取表格中的内容 if (i < 4 - 1) { test1 = test1 + ","; } else { test1 = test1 + "}"; } } //document.getElementById("showTest").innerHTML = test1; //var cc = eval("("+test1+")");//将文本转换为json对象 //alert(cc["cc01"].toString().trim());//js读取json的方式 } function get() { getTestValue(); var test = { "cc": "aa", "bb": "dd", "ee":eval("("+test1+")") } document.getElementById("showTest").innerHTML = JSON.stringify(test); alert(test["ee"]["cc21"].toString().trim());//js中json内容的访问方式 } </script> <title></title> </head> <body> <div id="test"> </div> <div id="showTest"> </div> <button id="Table" onclick="test()">生成Html代码层框架</button> <button onclick="get()">获取输入的值</button> </body> </html>
json的获取与添加,分享以备忘。