当有类似于章节梯级这样的显示需求时,前端如何遍历章节数据呢?可能表结构不同,方式也不同,这里介绍一下章节在一张表中的遍历方式。
先看表结构:
前台发送请求(注意:章节查询必须排好序,确保得到的数据升序排列,即sql语句加order by),得到数据(包括了遍历章节的代码):
<body>
<div>
</div>
<script src="../content/js/jquery-1.8.3.js"></script>
<script>
$.ajax({
url:"http://localhost:8000/studypaper//backend/guardianLesson/selectGuardianLesson",
data:{lessionId:1},
type:"get",
success:function(result){
var mark=0;//章的标记变量
var chapter=new Array();//章的存储数组
//得到所有的章
$.each(result.data.guardianLessonDetailList,function(index,element){
if(element.chapterNumber!=mark){
chapter.push(element);
mark=element.chapterNumber;
}
});
//遍历章
$.each(chapter,function(index,element){
var chapterContent="";
chapterContent+="<ul>第"+element.chapterNumber+"章:"+element.chapterTitle;
//遍历章下的节
$.each(result.data.guardianLessonDetailList,function(i,e){
var section="";
if(e.chapterNumber==element.chapterNumber){
section+="<li>第"+e.chapterIndex+"节:"+e.detailContent+"</li>";
}
chapterContent+=section;
});
chapterContent+="</ul>";
$("div").append(chapterContent);
});
}
});
</script>
</body>
得到的数据:
js遍历章节思路:1,创建一个数组,遍历所有的章节,取出所有的章,存放在数组中;1,遍历存放章的数组,并且在本次循环中再次遍历所有章节,取出章下面的所有的节。(详细写法:见上面代码)
显示效果如下: