我正在尝试将json添加到菜单中并在前端显示它。我通过javascript中的递归调用创建了一个HTML树结构,我可以在Web控制台中看到该结构似乎没问题。问题是我只是在菜单中看到父对象,子对象不会显示为子菜单。我无法弄清楚代码中的问题,需要一些帮助。
这是我的javascript代码:
$(function() {
addMenuItems = function(parentMenuItem, currentNode){
var divElement = document.createElement('div');
// set the text for the list item
divElement.innerHTML = currentNode.name;
var listItem = document.createElement('li');
listItem.appendChild(divElement);
var currentMenuItem = document.createElement('ul');
console.log("html current: " + parentMenuItem.innerHTML);
console.log("html parent: " + listItem);
// create the menu
var child;
for (child = 0; child < currentNode.children.length; child++){
addMenuItems(currentMenuItem, currentNode.children[child]);
}
// add a submenu list to this list
if(currentNode.children.length > 0){
listItem.appendChild(currentMenuItem);
}
// add the child to the menu
parentMenuItem.appendChild(listItem);
console.log("html: " + parentMenuItem.innerHTML);
};
//End of function
$("#menu").hide()
var identifiedObjects = [];
$("#Boma").mousedown(function(e) {
if(e.button==2){
var browserCoord = {x:e.pageX, y:e.pageY};
console.log(browserCoord);
}
});
document.getElementById("Boma").oncontextmenu = function () {return false;}
$("#Boma").mousedown(function(e) {
if(e.button==2)
{
$("#menu").css('left', e.pageX+5);
$("#menu").css('top', e.pageY+5);
$("#menu").fadeIn(100);
$( "#menu" ).menu();
}
});
$(document).click(function(e) {
if(e.button==0){
$("#menu").fadeOut(80);
}
});
jQuery.getJSON("/new_veg.json", (data) => {
console.log(data);
addMenuItems(document.getElementById('menu'), data);
});
});
这是json:
{
"name":"vegetation",
"id":"2",
"children":[
{
"name":"landuse",
"id":"2.1",
"children":[
{
"name":"forest area",
"id":"2.1.1",
"children":[]
},
{
"name":"plantation",
"id":"2.1.2",
"children":[]
}
]
}
]
}