研究了一下递归循环,展示留言评论功能,如图
代码部分:基于jquery开发
js部分
$(function(){
var array = [
{id:1,name:'张一',time:'2017-12-06',data:[
{id:2,name:'张二',time:'2017-12-06',
data:[
{id:22,name:'张三',time:'2017-12-06'},{id:23,name:'张四',time:'2017-12-06'}
]
},
{id:3,name:'张五',time:'2017-12-06'}
]},
{id:4,name:'张刘曼',time:'2017-12-06',data:[
{id:5,name:'张六',time:'2017-12-06'},{id:6,name:'张七',time:'2017-12-06'}
]},
{id:7,name:'张吧',time:'2017-12-06',data:[
{id:8,name:'张就',time:'2017-12-06'},{id:9,name:'张是',time:'2017-12-06'}
]},
{id:10,name:'张三一',time:'2017-12-06',data:[
{id:11,name:'张三二',time:'2017-12-06'},{id:12,name:'张三撒',time:'2017-12-06'}
]},
{id:13,name:'张三四',time:'2017-12-06',data:[
{id:14,name:'张三五',time:'2017-12-06'},{id:15,name:'张三六',time:'2017-12-06'}
]},
{id:16,name:'张三七',time:'2017-12-06'},
{id:17,name:'张三吧',time:'2017-12-06'},
{id:18,name:'张三就',time:'2017-12-06'}
];
var html = '',sw = 1;
listShow(array);
$('.messageBox').append(html);
function listShow(array){
for(var i = 0;i<array.length; i++){
if(array[i].data){
html+=`<li>
<div>
<span><i class="zheicon comicon"></i>${array[i].id}</span>
<span>${array[i].name}</span>
<span>好漂亮</span>
<span>${array[i].time}</span>
</div><ul>`;
//递归回调
listShow(array[i].data);
html+='</ul></li>';
}else{
html+=`<li>
<div>
<span>${array[i].id}</span>
<span>${array[i].name}</span>
<span>好漂亮</span>
<span>${array[i].time}</span>
</div></li>`;
}
}
}
//点击展开
$('.messageBox').on('click','.zheicon',function(){
var zheBox = $(this).parent().parent().siblings('ul');
if($(zheBox).hasClass('show')){
$(zheBox).removeClass('show');
}else{
$(zheBox).addClass('show');
}
});
})
html部分
<ul class="messageBox">
<li class="msg-head">
<div class="">
<span>ID</span>
<span>评论人</span>
<span>评论内容</span>
<span>评论时间</span>
</div>
</li>
</ul>
CSS部分
.messageBox {
width: 100%;
height: auto;
position: relative;
padding: 0;
margin: 0;
box-sizing: border-box;
border: 1px solid #eee;
overflow: visible;
}
.messageBox li {
width: 100%;
padding-left: 30px;
box-sizing: border-box;
list-style-type: none;
position: relative;
background: #fff;
transition: background 0.3s ease;
}
.messageBox li div {
width: 100%;
padding-left: 30px;
box-sizing: border-box;
position: relative;
}
.messageBox li div span {
width: 25%;
height: 40px;
line-height: 40px;
box-sizing: border-box;
float: left;
}
.messageBox li div:after {
content: '';
display: block;
clear: both;
}
.messageBox li li:nth-child(odd) {
background: transparent;
}
.messageBox li li:last-child {
border-bottom: none;
}
.messageBox li ul {
display: none;
margin: 0;
padding: 0;
}
.messageBox li ul li {
background: transparent;
}
.messageBox li ul.show {
display: block;
}
.messageBox li .zheicon {
display: inline-block;
width: 0px;
height: 0px;
border-left: 8px solid transparent;
border-right: 8px solid transparent;
border-top: 8px solid#2f2f2f;
position: absolute;
left: 8px;
top: 15px;
}
.messageBox li:nth-child(odd) {
background: #f8f8f8;
}
.messageBox .msg-head {
background: #f8f8f8;
}