<! DOCTYPE html >
< html lang = " en" > < head> < meta charset = " UTF-8" > < meta name = " viewport" content = " width=device-width, initial-scale=1.0" > < title> 实现当前元素的同级元素 以及父元素的同级元素</ title> < style> </ style>
</ head> < body> < div id = " category" > </ div> < script> const categories = [ { id : 1 , name : "电子产品" , parent : 0 } , { id : 2 , name : "手机" , parent : 1 } , { id : 3 , name : "苹果" , parent : 2 } , { id : 4 , name : "小米" , parent : 2 } , { id : 5 , name : "华为" , parent : 2 } , { id : 6 , name : "电脑" , parent : 1 } , { id : 7 , name : "笔记本" , parent : 6 } , { id : 8 , name : "台式机" , parent : 6 } , { id : 9 , name : "服装" , parent : 0 } , { id : 10 , name : "男装" , parent : 9 } , { id : 11 , name : "衬衫" , parent : 10 } , { id : 12 , name : "裤子" , parent : 10 } , { id : 13 , name : "女装" , parent : 9 } , { id : 14 , name : "裙子" , parent : 13 } , { id : 15 , name : "上衣" , parent : 13 } , { id : 16 , name : "萝莉" , parent : 13 } , { id : 17 , name : "御姐" , parent : 13 } , ] ; const container = document. getElementById ( "category" ) ; function test ( currentId ) { const item = categories. find ( ( category ) => category. id === currentId) ; const parentId = item. parent; const items = categories. filter ( ( category ) => category. parent === parentId) ; const sel = document. createElement ( "select" ) ; sel. add ( new Option ( "-请选择-" , - 1 ) ) ; items. forEach ( child => { const option = new Option ( child. name, child. id) ; sel. add ( option) ; } ) ; container. insertBefore ( sel, container. firstChild) ; if ( parentId != 0 ) { test ( parentId) ; } } test ( 17 ) ; </ script> </ body> </ html>