用html文件实现一个简单的遍历数组并输出到页面上面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>常见问题</title>
<style>
html {
width: 100%;
}
.contant {
width: 600px;
margin: 50px auto;
}
.top-title {
text-align: center;
font-size: 30px;
}
.item-wrap{
margin-top: 50px;
}
.left-circle {
width: 12px;
height: 12px;
border-radius: 6px;
background: black;
display: inline-block;
}
.item-title {
font-size: 26px;
font-weight: bold;
}
.item-question {
margin-top: 20px;
font-weight: bold;
font-size: 20px;
}
.item-answer {
margin-top: 10px;
font-size: 18px;
// margin-left: 10px;
line-height: 28px;
}
</style>
</head>
<body>
<div class="contant">
<p class="top-title">常见问题</p>
<div id="mainID">
</div>
</div>
</body>
<script>
var mainStr = ""
//自定义数组
var mainArr = [
{
title: '这是第一级',
children:
[
{
question: '这是第一级1-1',
answer: '这是第一级1-1描述'
},
{
question: '这是第一级1-2',
answer: '这是第一级1-2描述',
}
]
},
{
title: '这是第二级',
children: [
{
question: '这是第二级2-1',
answer: '这是第二级2-1描述'
},
{
question: '这是第二级2-2',
children: [
'这是第二级2-2-1',
'(这是第二级2-2-2']
}]
},
{
title: '这是第三级',
children:
[
{
question: '这是第三级3-1',
answer: '这是第三级3-1描述'
},
]
}
];
/*
*.join('')的作用是去掉map循环后返回多余的逗号
*/
mainArr.forEach(e => {
mainStr += `<div class="item-wrap">
<div class="item-title">${e.title}</div>
<div class="text">
${e.children.map((element, index) => {
let ele = `<p class="item-question">${index + 1}.${element.question}</p>`
if(element.children!=undefined){
element.children.forEach(item=>{
ele += `<p class="item-answer">${item}</p>`
})
}else{
ele += `<p class="item-answer">${element.answer}</p>`
console.log(element.children)
}
return ele
}).join('')}
</div>
</div>`
})
//拼接完字符串数组后用innerHTML把它渲染到页面中
document.getElementById("mainID").innerHTML = mainStr;
</script>
</html>
如下图所示: