纯JS实现无限极分类
<!DOCTYPE html> <html> <head> <title></title>
//引入Jquery <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script> <style type="text/css"> .one{ background: red; } .two{ background-color: green; margin-left: 30px; } .three{ background-color: yellow; margin-left: 60px; } li{ list-style: none; border: 1px red solid; margin-top:10px; width: 200px; } </style> </head> <body> <div id="add"> <!-- <li class="one">上衣</li> <li class="two">男装</li> <li class="three">男西装</li> --> </div> </body> <script type="text/javascript">
//首先定义一个数组,分类是按照父级分类pid来判断的
var arr=[ {id:1,name:"上衣",pid:0}, {id:2,name:"裤子",pid:0}, {id:3,name:"鞋子",pid:0}, {id:9,name:"电子",pid:0}, {id:4,name:"男装",pid:1}, {id:5,name:"男皮衣",pid:4}, {id:6,name:"男西装",pid:4}, {id:7,name:"休闲裤",pid:2}, {id:8,name:"手机",pid:9}, ]
//用的是3层foreach循环 arr.forEach(function(value, index, array) { // console.log(value.name+"-----"+index+"----"+array); if (value.pid==0) { // console.log(value.name);
//如果是顶级分类的话,就用class=one的li标签
var one="<li class='one'>"+value.name+"</li>"; $("#add").append(one); arr.forEach(function(value1,index1){ if(value1.pid==value.id){
//如果是二级分类,就用class=two 的li标签 var two="<li class='two'>"+value1.name+"</li>"; $("#add").append(two); arr.forEach(function(value2,index2){ if(value2.pid==value1.id){
//如果是三级分类,就用class=three的li标签 var three="<li class='three'>"+value2.name+"</li>"; $("#add").append(three); } }) } }) } }); </script> </html>