1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| var para = { span: { div:{ span: [ { id: "span1", content: "span1" }, { id: "span2", content: "span2" }, { id: "span3", content: "span3" }], div: { img:[ { id: "我就是个img", content:"img" } ], outer: { id: "第三层的div", content: "div" } }, p:[{ id: "我就是个p", content: "p" }], outer: { id: "第二层的div", content: "div" }}, span: [{ id: "span0", content: "span0" }], outer: { id: "第一层的div", content: "div" } }, outer: null }
var contentHtml = ""; var outterTag = ""; function genereateEngine(para,outter,outterTag,pureHtml){
for(var i in para){ if(Object.prototype.toString.call(para[i]) === "[object Object]"){
outterTag = i; if(i === "outer"){ return pureHtml; }
var unitHtml = genereateEngine(para[i],i,outterTag, ""); var attr = " "; for(var j in para[i].outer){ if(j !== "content") { attr += j + "='"+ para[i].outer[j] + "' "; } } attr = attr.substr(0, attr.length - 1);
unitHtml = '<' + outterTag + attr+'>' + unitHtml + para[i].outer.content + '</' + outterTag + '>'; contentHtml = pureHtml + unitHtml; pureHtml = pureHtml + unitHtml; } else if(Object.prototype.toString.call(para[i]) === "[object Array]"){ var tempoHtml = newUnitModel(i,para[i]); pureHtml += tempoHtml; } else if(para[i] === null){ console.log("解析完成"); return contentHtml; } else{ console.log(i); console.log("传入的数据非法,解析失败"); } } }
function newUnitModel(tag, content){ var sameCatalog = "";
for(var i=0; i<content.length; i++) { var attr = " ";
for(var j in content[i]){ if(j !== "content") { attr += j + "='"+ content[i][j] + "' "; } } attr = attr.substr(0, attr.length - 1); sameCatalog += ("<" + tag + attr + ">" + content[i].content + "</" + tag + ">"); } return sameCatalog; } var result = genereateEngine(para,"","",""); console.log(result)
|