Semasa projek baru-baru ini, saya perlu menjana direktori seperti pepohon berdasarkan data JSON Kod yang terhasil adalah seperti berikut:
var folderList=[ { "FolderName": "ASD", "ChildList": null }, { "FolderName": "内网公告", "ChildList": null }, { "FolderName": "测试文档", "ChildList": null }, { "FolderName": "软件开发", "ChildList": null }, { "FolderName": "Test", "ChildList": [ { "FolderName": "Test2", "ChildList": [ { "FolderName": "Test3", "ChildList": null } ] } ] }, { "FolderName": "个人", "ChildList": null }, { "FolderName": "公司通知", "ChildList": null }, { "FolderName": "采购平台", "ChildList": null } ]; var str=''; function generateFolders(arr) { if (arr.length > 0) { str += '<div class="sui-list sui-list-icon ubt bc-gra1">'; for (var i = 0, len = arr.length; i < len; i++) { str += '<ul class="ub ub-ac">' + '<li class="sui-list-licon sui-icon-ok-circle fts2">' + '</li>' + '<ul class="ub ub-f1 sui-list-item">' + '<li class="ub-f1 sui-list-text sui-list-nowrap">' + arr[i].FolderName + '</li>' + '<li class="sui-list-ricon ub-img sui-icon-chevron-right fts2"></li>' + '</ul>' + '</ul>'; if (isDefine(arr[i].ChildList)) { str += generateFolders(arr[i].ChildList); } } str += '</div>'; return str; }else{ return ''; } } var folderTxt ='<div class="sui-list sui-list-icon ubt bc-gra1">' +'<ul class="ub ub-ac">' +'<li class="sui-list-licon sui-icon-drawer fts2">' + '</li>' +'<ul class="ub ub-f1 sui-list-item">' +'<li class="ub-f1 sui-list-text sui-list-nowrap">我的目录</li>' +'<li class="sui-list-ricon ub-img sui-icon-chevron-right fts2"></li>' +'</ul>' +'</ul>'; folderTxt+=generateFolders(folderList); folderTxt += '</div>'; $('#list').html(folderTxt); /** * 判断是否是空 * @param value */ function isDefine(value){ if(value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof(value) == 'undefined'){ return false; } else{ value = value+""; value = value.replace(/\s/g,""); if(value == ""){ return false; } return true; } }
Pokok yang terhasil adalah seperti di bawah:
Selepas penyiasatan, didapati masalah itu disebabkan oleh lokasi definisi str yang salah. Hanya tentukan str sebagai pembolehubah setempat.
function generateFolders(arr) { var str=''; if (arr.length > 0) { str += '<div class="sui-list sui-list-icon ubt bc-gra1">'; for (var i = 0, len = arr.length; i < len; i++) { str += '<ul class="ub ub-ac">' + '<li class="sui-list-licon sui-icon-ok-circle fts2"></li>' + '<ul class="ub ub-f1 sui-list-item">' + '<li class="ub-f1 sui-list-text sui-list-nowrap">' + arr[i].FolderName + '</li>' + '<li class="sui-list-ricon ub-img sui-icon-chevron-right fts2"></li>' + '</ul>' + '</ul>'; if (isDefine(arr[i].ChildList)) { str += generateFolders(arr[i].ChildList); } } str += '</div>'; return str; }else{ return ''; } }
Selepas pengubahsuaian, kesan yang diingini boleh dicapai:
Di atas adalah keseluruhan kandungan artikel ini, saya harap anda semua menyukainya.