-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday1021-build-dom.html
125 lines (115 loc) · 3.26 KB
/
day1021-build-dom.html
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>以下列虚拟对象添加对应的标签到页面上</title>
</head>
<body>
<section></section>
<section></section>
<script>
/*
将这个虚拟节点数据 具象化成实际标签
*/
var element = {
tagName: 'div',
id: 'header',
className: 'title fw400 c666 fz28',
contentText: '我是一个header标签',
children: [
{
tagName: 'h1',
id: '',
className: 'logo',
contentText: '我是logo',
children: []
},
{
tagName: 'ul',
id: '',
className: 'nav',
contentText: '',
children: [
{
tagName: 'li',
id: '',
className: 'list',
contentText: '导航1',
children: []
},
{
tagName: 'li',
id: '',
className: 'list',
contentText: '导航2',
children: []
},
{
tagName: 'li',
id: '',
className: 'list',
contentText: '',
children: [
{
tagName: "img",
id: '',
className: '',
contentText: '',
src: 'https://placehold.co/60x60',
width: '60',
height: '60',
alt: 'a 60x60 picture',
children: []
}
]
},
]
}
]
};
function buildDom(root) {
var rootElem = document.createElement(root.tagName);
for (const key in root) {
switch (key) {
case "tagName":
// this case is handled above
break;
case "contentText":
rootElem.textContent = root[key];
break;
case "alt":
rootElem[key] = root[key] || " ";
break;
default:
if (root[key] !== "") {
rootElem[key] = root[key];
}
break;
}
}
rootElem.append(...root.children.map(n => buildDom(n)));
return rootElem;
}
function buildDomInnerHTML(root) {
function attrText(r) {
var attrs = Object.assign({}, r);
delete attrs["tagName"];
delete attrs["contentText"];
delete attrs["children"];
attrs["class"] = attrs["className"];
delete attrs["className"];
return Object.entries(attrs).filter(kv => kv[1] !== "")
.map(kv => `${kv[0]}="${kv[1]}"`)
.concat(["alt"].filter(k => attrs[k] === "").map(k => `${k}=" "`))
.join(" ");
}
var childText = root.children.map(c => buildDomInnerHTML(c)).join("");
var rootElem = `<${root.tagName} ${attrText(root)}>${root.contentText ?? ""}${childText}</${root.tagName}>`;
return rootElem;
}
document.querySelector('section:nth-of-type(1)').append(buildDom(element));
document.querySelector('section:nth-of-type(2)').innerHTML = buildDomInnerHTML(element);
</script>
</body>
</html>