We mainly use recursion and iteration to traverse json members to generate html elements. The better thing is that num can write a lot of code for the number of loops. For specific applications, we see json-to-html trio.
Raw Material: json
The Code is as follows:
Var json = {
'P': {id: 'flower', className: "a1", sub :[
{
'U': {id: 'flower1', className: ["a2", "a3"], sub :[
{'Lil': {num: 3, con: "content", fn: {'click': function () {alert ('I am lili ')}}}}
]}
},
{
'Ul ': {id: 'flower4', className: ["a2", "a3"], sub :[
{'Lil': {num: 3, con: "2nd rounds", fn: {'click': function () {alert ('I am lili ')}}}}
]}
},
{
'Span ': {id: 'Q', con: "I am span "}
}
]}
}
Id = id
ClassName = class
Num = number of cycles
Fn = binding function
Con = Element Content
Sub = indicates that a subnode exists.
Main course: method
The Code is as follows:
JsonToHtml = {
Init: function (data, parent) {// jsonDB, parent Element
For (var attr in data ){
If (data [attr] ["id"]) {var num = 1} else {var num = data [attr] ["num"] | 1} // If an id exists, the loop defaults to 1 because the id cannot be repeated.
For (var j = 0; j Var obj = document. createElement (attr );
Parent? Parent. appendChild (obj): document. body. appendChild (obj); // input the parent element when recursion occurs. If not, the parent element is output from the body by default.
For (var attr2 in data [attr]) {
Var _ tempAttr = data [attr] [attr2];
Switch (attr2 ){
Case "id ":
Obj. id = _ tempAttr;
Break;
Case "className": // multiple classes are supported ~ Simplified ~
If (_ tempAttr. length & _ tempAttr. pop ){
For (var k = 0; k <_ tempAttr. length; ++ k ){
Obj. className = obj. className + "" + _ tempAttr [k];
}
} Else {obj. className = _ tempAttr ;}
Break;
Case "sub": // recursion starts if a subnode exists.
For (var I = 0; I <_ tempAttr. length; I ++ ){
_ TempAttr [I]. sub? This. init (_ tempAttr [I]): this. init (_ tempAttr [I], obj)
}
Break;
Case "con": // set content to generate new child elements
Obj. innerHTML = _ tempAttr;
Break;
Case "num ":
Break;
Case "fn": // binding method
For (var fns in _ tempAttr ){
If (window. addEventListener ){
Obj. addEventListener (fns, _ tempAttr [fns], false );
} Else {
If (window. attachEvent ){
Obj. attachEvent ("on" + fns, _ tempAttr [fns]);
}
}
}
Break;
Default: // set attributes
Obj. setAttribute (attr2, _ tempAttr); break;
}
}
}
}
Return this;
}
}
JsonToHtml. init (json); // Initialization
Serving
The Code is as follows:
- 2nd rounds
- 2nd rounds
- 2nd rounds
I am a span
It mainly uses recursion and iteration to traverse json members to generate html elements. It is better that num can specify the number of cycles and write a lot of code less. The specific application depends on the scenario.
This is just a small example. We are looking forward to the future!