[英]how to create DOM element structure in javascript
我有这段代码,我需要将 ti 转换为 DOM 结构(更多信息如下)
const data = [
{
"type": "paragraph",
"children": [
{
"type": "text",
"text": "Hey all!"
},
{
"type": "break"
},
{
"type": "break"
},
{
"type": "text",
"text": " It's been a while since we partied "
},
{
"type": "important",
"children": [
{
"type": "text",
"text": "together"
}
]
},
{
"type": "text",
"text": " in a pool full of people!"
}
]
},
{
"type": "heading",
"id": "table-of-contents",
"level" : 2,
"children": [
{
"type": "text",
"text": "Table of contents:"
}
]
},
{
"type": "list",
"bullet": "decimal",
"children": [
{
"type": "listitem",
"children": [
{
"type": "anchor",
"href": "#table-of-contents",
"children": [
{
"type": "text",
"text": "How to start a podcast?"
},
{
"type": "text",
"text": ""
}
]
},
{
"type": "text",
"text": "Where to find your topics?"
}
]
},
{
"type": "listitem",
"children": [
{
"type": "text",
"text": "Where to find your topics?"
}
]
},
{
"type": "listitem",
"children": [
{
"type": "text",
"text": "What equipment do you need?"
}
]
}
]
}
]
最好的方法是什么?
我的意思是,我应该这样做
const wrapper = document.createElement("div");
data.forEach(element => {
if(element.type === "paragraph") {
const paragraph = document.createElement("p");
element.children.forEach(kiddo => {
if(kiddo.type === "text") {
const textNode = document.createTextNode(kiddo.text);
paragraph.appendChild(textNode);
}
});
}
})
..等等? 我的意思是我必须使用“createElement/createTextNode”函数还是 javascript 有某种 DOMBuilder,而不是我可以将这种结构转换为 DOM?
正如 Teemu 所说,您可以通过向 object 添加方法并递归来创建自己的“DOM Builder”。
const body = document.getElementsByTagName("body")[0];
const wrapper = document.createElement("div");
const DOMBuilder = {
"anchor" : e => {
var a = document.createElement("a");
a.href = e.href;
return a;
},
"heading" : e => { return document.createElement("h" + e.level); },
"list" : e => {
return document.createElement((e.bullet == "decimal") ? "ol" : "ul");
},
"listitem" : () => { return document.createElement("li"); },
"paragraph" : () => {return document.createElement("p"); },
"text" : e => {return document.createTextNode(e.text); },
}
function CreateDOMElement(e) {
var ne;
if (ne = DOMBuilder[e.type]?.(e)) {
if (e.id) ne.id = e.id;
e.children?.forEach(c => {
var ce = CreateDOMElement(c); if (ce) ne.appendChild(ce);
});
return ne;
}
}
data.forEach(element => {
var ne = CreateDOMElement(element); if (ne) wrapper.appendChild(ne);
});
body.appendChild(wrapper);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.