As we all know: the template engine is a solution for converting data into views. What are the solutions before this?
body structure
<body>
<ul id="list">
</ul>
</body>
Pure DOM method
var arr = [
{"name":"小明","age":12,"sex":"男"},
{"name":"小红","age":11,"sex":"女"},
{"name":"小强","age":13,"sex":"男"}
]
// 纯dom很笨拙 这里只简单演示
// 创建文档碎片 减少往真实dom中添加元素的次数,减少渲染次数 优化性能
const frag = document.createDocumentFragment()
const list = document.querySelector('#list')
for (let i = 0; i < arr.length; i++) {
let li = document.createElement('li')
li.innerHTML = arr[i].name
frag.appendChild(li)
}
list.appendChild(frag)
Array join method
Because it is very troublesome to wrap the string before the template string
So you can put the string into an array, and then integrate the string through the Join method of the array.
Note: In vscode, hold down the alt key and use the multi-line cursor to quickly add ' and comma to the label
var arr = [
{"name":"小明","age":12,"sex":"男"},
{"name":"小红","age":11,"sex":"女"},
{"name":"小强","age":13,"sex":"男"}
]
// 创建文档碎片 减少往真实dom中添加元素的次数,减少渲染次数 优化性能
const frag = document.createDocumentFragment()
const list = document.querySelector('#list')
for (let i = 0; i < arr.length; i++) {
let li = document.createElement('li')
li.innerHTML = [
'<li>',
'<p>'+arr[i].name+'</p>',
'<h2><span>'+arr[i].age+'</span>',
'<span>'+arr[i].sex+'</span>',
'</h2>',
'</li>',
].join('')
frag.appendChild(li)
}
list.appendChild(frag)
es6 template string method
This is also the most convenient among non-template engines currently.
Just add ${} in backticks to manipulate variables
var arr = [
{"name":"小明","age":12,"sex":"男"},
{"name":"小红","age":11,"sex":"女"},
{"name":"小强","age":13,"sex":"男"}
]
// 纯dom很笨拙 这里只简单演示
// 创建文档碎片 减少往真实dom中添加元素的次数,减少渲染次数 优化性能
const frag = document.createDocumentFragment()
const list = document.querySelector('#list')
for (let i = 0; i < arr.length; i++) {
let li = document.createElement('li')
li.innerHTML = `
<li>${arr[i].name}</li>
<p>已经</p>
<span>${arr[i].age}岁了</span>
<span>性别${arr[i].sex}</span>
`
frag.appendChild(li)
}
list.appendChild(frag)