JS遍历2层DOM装入数组转JSON【实例】
XML/HTML代码
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- <style>
- *{ margin:0; padding:0;}
- body{ color:#333; font-family:'Microsoft Yahei'; font-size:16px;}
- ul,li{ list-style:none; line-height:30px;}
- .conbox{ padding:10px;}
- .conbox .selected{ color:#CC0033}
- .conbox .lis span{ padding:0 5px;}
- </style>
- </head>
- <body arrData="111,222,333,444,555,666">
- <div class="conbox">
- <ul class="lisbox">
- <li data-qId="11" n="aaa" class="lis selected"><span class="on">111c</span><span class="on">222c</span><span class="on">333c</span></li>
- <li data-qId="22" n="bbb" class="lis">bbb</li>
- <li data-qId="33" n="ccc" class="lis selected"><span class="on">111a</span><span class="on">222a</span><span class="on">333a</span></li>
- <li data-qId="44" n="ddd" class="lis">ddd</li>
- <li data-qId="55" n="eee" class="lis selected"><span class="on">111b</span><span class="on">222b</span><span class="on">333b</span></li>
- <li data-qId="66" n="fff" class="lis">fff</li>
- </ul>
- </div>
- <div id="submitBtn" style=" width:100%; height:50px; line-height:50px; text-align:center; color:#fff; background:#CC0000">点击事件</div>
- </body>
- <script type="text/javascript" src="http://code.liuxinxiu.com/lib/zepto/zepto-1.1.6.js"></script>
- <script type="text/javascript">
- $("#submitBtn").on("click",function(){
- /********* 声明变量获取节点 ***************/
- var qList=$(".lisbox li.selected"),qLen=qList.length,arr=[];
- /********* 循环第一层问题 ***********/
- for(var i=0;i<qLen;i++){
- /**** var $anList=$qList.eq(i).find("[name=an" + i + "]:checked"),subArr=[]; ****/
- var anList=qList.eq(i).find(".on"),subArr=[];
- var qid=qList.eq(i).attr("data-qId");
- /***** 循环第二层答案 **********/
- for(var key=0;key<anList.length;key++){
- subArr.push(anList.eq(key).text());
- }
- /***** 添加到整体数组 ************/
- arr.push({Question:qid,Answer:subArr});
- }
- /***** 转化成JSON结构字符串 *******/
- var subArrst=JSON.stringify(subArr);
- var jsondata=JSON.stringify(arr);
- /***** 使用replace替换"号为空、可全部 ******/
- var _subArrst=subArrst.replace(/"/g,"");
- var _datalist=jsondata.replace(/"/g,"");
- var _dataJson={guId:111222,eventId:11,plat:5,datalist:subArrst};
- alert(_datalist)
- });
- </script>
- </html>