将对象列表转换为嵌套UL不起作用

Transforming list of objects into nested UL not working

本文关键字:嵌套 UL 不起作用 转换 对象 列表      更新时间:2023-09-26

我正试图将通过ajax获得的对象列表转换为类别菜单的嵌套ul。在浏览了这个网站后,我发现了一个PHP函数,并将其转换为javascript。

不幸的是,它不起作用:

function has_children(data, id) {
    for(a=0; a<data.length; a++) {
        if (data[a].ParentID == id) return true;
    }
    return false;
}
function renderCategoryTree(data, parent) {
    result = "<ul>";
    for(index=0; index<data.length; index++) {
        if (data[index].ParentID == parent) {
            result = result + "<li>" + data[index].Name;
            if (has_children(data, data[index].ID)) 
                result = result + renderCategoryTree(data, data[index].ID);
            result = result + "</li>";
        }
    }
    result = result + "</ul>";
    return result;
}
var stuff= [ { ID: 1, ParentID: 0, Name: 'Development' },
{ ID: 2, ParentID: 0, Name: 'Databases' },
{ ID: 3, ParentID: 0, Name: 'Systems' },
{ ID: 4, ParentID: 1, Name: 'java' },
{ ID: 5, ParentID: 1, Name: 'c++' },
{ ID: 6, ParentID: 1, Name: 'python' },
{ ID: 7, ParentID: 1, Name: 'ruby' },
{ ID: 8, ParentID: 2, Name: 'mysql' },
{ ID: 9, ParentID: 2, Name: 'oracle' },
{ ID: 10, ParentID: 2, Name: 'sqlite' },
{ ID: 11, ParentID: 3, Name: 'linux' },
{ ID: 12, ParentID: 3, Name: 'windows' } ];
  alert(renderCategoryTree(stuff, 0));

渲染在"ruby"处停止。我认为问题出在javascript打字的工作方式上,但我不确定。有人能帮忙吗?谢谢

我不能100%确定,但我认为您的循环计数器是全局的。所以如果你写

for(var a=0; a<data.length; a++) {

而不是

for(a=0; a<data.length; a++) {

for(var index=0; index<data.length; index++) {

而不是

for(index=0; index<data.length; index++) {

它会起作用的。

我发现了问题:因为javascript变量在嵌套函数调用中幸存,所以必须使用var使它们成为本地变量。

只是为索引声明添加var就成功了!