首先,将数组分开
可以假设数组为:[{"txt":"测试1","pic":"测试pic1"},{"txt":"测试1","pic":"测试pic2"}]
则:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> </head> <body> <div id="container" style="border: 1px solid red;"></div> <script type="text/javascript"> //创建参数 var string = '[{"txt":"测试1","pic":"测试pic1"},{"txt":"测试1","pic":"测试pic2"}]'; //转换为对象 var stringObj = JSON.parse(string); //循环 for (var j in stringObj) { //创建"$container2",将一组元素放在一个div中 var $container2 = $('<div style="border: 1px solid red;margin: 5px" class="container2"></div>'); $('#container').append($container2); for (var i in stringObj[j]){ console.log(i,stringObj[j][i]); //显示每个数组中的具体元素 $container2.append('<div style="border: 1px solid blue;margin: 5px;"><span class="title">'+i+'</span><br><textarea class="content" style=" 100%">'+stringObj[j][i]+'</textarea></div>') } } </script> </body> </html>
效果图为:
可以对数组中的数据修改后在保存
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script> </head> <body> <!--=======================================================================--> <div id="container" style="border: 1px solid red;"></div> <div id="wrapper" style="border: 1px solid red"></div> <button>合并</button> <!--=======================================================================--> <script type="text/javascript"> //创建参数 var string = '[{"txt":"测试1","pic":"测试pic1"},{"txt":"测试1","pic":"测试pic2"}]'; //转换为对象 var stringObj = JSON.parse(string); //循环 for (var j in stringObj) { //创建"$container2",将一组元素放在一个div中 var $container2 = $('<div style="border: 1px solid red;margin: 5px" class="container2"></div>'); $('#container').append($container2); for (var i in stringObj[j]){ console.log(i,stringObj[j][i]); //显示每个数组中的具体元素 $container2.append('<div style="border: 1px solid blue;margin: 5px;"><span class="title">'+i+'</span><br><textarea class="content" style=" 100%">'+stringObj[j][i]+'</textarea></div>') } } //点击按钮,将每个元素重新放在数组中,然后以字符串的形式显示 $('button').click(function () { var newAry=[]; //$('#container .container2').each(function (index,element) { $('.container2').each(function (index,element) { var newObj = {}; $(element).find('div').each(function (index2,element2) { console.log($(element2).find('.title').text(),$(element2).find('.content').val()); var title = $(element2).find('.title').text(); var content = $(element2).find('.content').val(); newObj[title] = content; }); newAry.push(newObj); }); console.log(newAry); var newString = JSON.stringify(newAry); console.log(newString); $('#wrapper').text(newString); }); </script> </body> </html>
效果图为: