这是我的 JSON 文件,我想创建没有嵌套循环的 HTML 多级菜单
[{"text":"Home","href":"http://home.com","icon":"fas fa-home","target":"_top","title":"My Home"},{"text":"Posts","href":"","icon":"fas fa-bell","target":"_self","title":"","children":[{"text":"Sports","href":"","icon":"empty","target":"_self","title":""},{"text":"IT1","href":"","icon":"empty","target":"_self","title":""},{"text":"Web","href":"","icon":"","target":"_self","title":""},{"text":"About","href":"","icon":"fas fa-chart-bar","target":"_self","title":""}]}]
我写了这个,但我认为这不是最好的方法 感谢您的帮助
function MenuToHTML(JSON) {
let html = "<ul>";
for (items in JSON) {
html += "<li>";
//console.log(JSON[items].text);
html += JSON[items].text;
if (JSON[items].hasOwnProperty("children")) {
var child = JSON[items].children;
html += "<ul>";
for (subItems in child) {
html += "<li>";
html += child[subItems].text;
if (child[subItems].hasOwnProperty("children")) {
html += "<ul>";
var child = child[subItems].children;
for (SubsubItems in child) {
html += "<li>";
html += child[SubsubItems].text;
html += "</li>";
}
html += "</ul>";
}
html += "</li>";
}
html += "</ul>";
}
html += "</li>";
}
html += "</ul>";
return html;
}
最佳答案
您可以构建真实元素并对嵌套子元素使用递归。
function getMenu(array) {
return array.reduce((ul, { text, href, icon, target, title, children }) => {
var li = document.createElement('li'),
a;
if (href) {
a = document.createElement('a');
a.href = href;
a.target = target;
a.appendChild(document.createTextNode(text));
a.title = title;
li.appendChild(a);
} else {
li.appendChild(document.createTextNode(text));
}
if (children) {
li.appendChild(getMenu(children));
}
ul.appendChild(li);
return ul;
}, document.createElement('ul'));
}
var data = [{ text: "Home", href: "http://home.com", icon: "fas fa-home", target: "_top", title: "My Home" }, { text: "Posts", href: "", icon: "fas fa-bell", target: "_self", title: "", children: [{ text: "Sports", href: "", icon: "empty", target: "_self", title: "" }, { text: "IT1", href: "", icon: "empty", target: "_self", title: "" }, { text: "Web", href: "", icon: "", target: "_self", title: "" }, { text: "About", href: "", icon: "fas fa-chart-bar", target: "_self", title: "" }] }];
document.body.appendChild(getMenu(data));
关于javascript - 防止 JavaScript 中嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54619698/