温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js中DOM三级列表的示例分析

发布时间:2021-08-02 12:16:40 来源:亿速云 阅读:141 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关js中DOM三级列表的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

效果图:

js中DOM三级列表的示例分析

代码如下:

<!DOCTYPE HTML>
<html>
<head>
<title>联动菜单</title>
<meta charset="utf-8" />
</head>
<body>
 <div id="category"></div>
 <script>
 /*使用 HTML DOM 的方式实现联动菜单*/
 var categories=[
{"id":10,"name":'男装',"children":[
 {"id":101,"name":'正装'},
 {"id":102,"name":'T恤'},
 {"id":103,"name":'裤衩'}
]},
{"id":20,"name":'女装',"children":[
 {"id":201,"name":'短裙'},
 {"id":202,"name":'连衣裙'},
 {"id":203,"name":'裤子',"children":[
 {"id":2031,"name":'长裤'},
 {"id":2031,"name":'九分裤'},
 {"id":2031,"name":'七分裤'}
 ]},
]},
{"id":30,"name":'童装',"children":[
 {"id":301,"name":'帽子'},
 {"id":302,"name":'套装',"children":[
 {"id":3021,"name":"0-3岁"},
 {"id":3021,"name":"3-6岁"},
 {"id":3021,"name":"6-9岁"},
 {"id":3021,"name":"9-12岁"}
 ]},
 {"id":303,"name":'手套'}
]}
];
 (function(arr){
 var select=//创建select
 document.createElement("select");
 //将opt追加到select中
 select.add(new Option("-请选择-",-1));
 //遍历arr中每个商品类别对象
 for(var i=0;i<arr.length;i++){
 //将option追加到select中
 select.add(
 new Option(arr[i].name,arr[i].id)
 );
 }
 var fun=arguments.callee;
 //为select绑定onchange事件:
 select.onchange=function(){
 //this->.前的元素对象
 //获得this的parent,保存在变量parent中
 var parent=this.parentNode;
 //反复:只要this不是parent的最后一个子节点
 while(this!=parent.lastChild){
 //删除parent下的最后一个子节点
 parent.removeChild(parent.lastChild);
 }
 //获得当前select选中项的下标i
 var i=this.selectedIndex;
 if(i>0){//如果i>0
 //获得arr中i-1位置的商品类别对象的children,保存在变量subCate
 var subCate=arr[i-1].children;
 //调用fun(subCate)
 subCate!==undefined&&fun(subCate);
 }
 }
 //将select追加到id为category的父元素下
 document.getElementById("category")
 .appendChild(select);
 })(categories);
 </script>
</body>
</html>

关于“js中DOM三级列表的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI