【问题标题】:Javascript recursive for loop to auto-build menu structure not workingJavascript递归for循环自动构建菜单结构不起作用
【发布时间】:2015-01-12 18:09:22
【问题描述】:

很久以来我一直在摸不着头脑,但无法为此找到任何解决方案。在一个 twitter 引导主题中,我编写了这个函数来递归地构建导航菜单。目前,我将菜单结构放在一个包含 JSON 对象的列表中,但最终它将被动态获取。这是执行此操作的代码:

function createMenus() {
    //fill the menus in navbar dynamically.
    vars={};
    vars.title = "RAFinder";
    vars.menus = ['Home', 
    {'Student':['Search Jobs','Sent Applications', 'Find Professors', 'My Profile', 'Test Scores']},
    {'Professor':[
        {'Research Jobs':['Research Jobs', 'Search RA', 'Sent Applications', 'Find Students', 'Student Profiles', 'Students Past Jobs and Performance', 'My Profile']},
        {'Posted Jobs':['Contracts FixedHourly', 'Work Diary', 'Reviewevaluation of students performance']},
        {'Messages':['Inbox', 'Sent', 'Archive']},
        ]},
    'About','Contact'
    ];

    //$('#divmain').html('');
    for (var i=0;i<vars.menus.length;i++)
        populateMenu(vars.menus[i]);

    $('title').text(vars.title);
    $('.navbar-brand').text(vars.title);
}

如您所见,该结构由项目列表组成,这些项目可以是字符串(用于菜单)或 JSON 对象(用于进一步递归的子菜单)。这是递归执行此操作的 populateMenu:

function populateMenu(menu, parent='') {
    console.log(menu, parent);
    tp=type(menu);
    if (tp=="string")
    {
        //Just fill menu.
        $('#divmain').append(parent + '::' + menu + '<br>');
        addMenuItem(menu, parent, false); //actually add it on bootstrap navbar
    }
    else if (tp=="object")
    {
        $('#divmain').append('Length of dict is: ' + Object.keys(menu).length.toString() + '<br>');
        k='';
        for (var key in menu) //this should ideally be one loop
        {
            //if (menu.hasOwnProperty(k)) {
            //  }
            console.log('ITERATING::',key);
            k = key;
        }
            //else {$('#divmain').append('notOwnProperty: ' + k);}

            //just fill k
            $('#divmain').append(parent + '::' + k.toString() + '-><br>');
            addMenuItem(k.toString(), parent, true);   //actually add it on bootstrap navbar
            l = menu[k];
            //for(item in l)
            for(var i=0;i<l.length;i++)
            {
                //$('#divmain').append(k + '::' + l[item] + '-><br>');
                $('#divmain').append('Now calling populateMenu for dict ' + l[i].toString()  + ' and parentIs: ' + k.toString() + '<br>');
                populateMenu(l[i], k.toString()); //these are dropdowns
            }
    }
}

根级菜单填写正常(即家庭、学生、教授、关于、联系人)。即使是学生子菜单也可以填满。问题在于教授子菜单。仅填充列表中的第一个 JSON 对象,即“研究工作”。其余的只是被 for 循环忽略了,我不明白为什么。

【问题讨论】:

    标签: javascript json twitter-bootstrap


    【解决方案1】:

    最后,我通过以下方式解决了这个问题:

    function createMenus() {
        //fill the menus in navbar dynamically.
        vars.menus = ['Home', 
        {'Student':['Search Jobs','Sent Applications', 'My Profile']},
        {'Professor':[
            {'Research Jobs':['Search RA', 'Sent Applications', 'Find Students', 'Student Profiles', 'Students Past Jobs and Performance']},
            {'Posted Jobs':['Contracts FixedHourly', 'Work Diary', 'Review/Evaluation of students performance']},
            {'Messages':['Inbox', 'Sent', 'Archive']},
            ]},
        'About','Contact'
        ];
    
        buildMenu(vars.menus, $('.navbar-nav'));
    }
    
     function buildMenu(arr, parentEl) {
        arr.forEach(function(root) {
            var li;
            var id;
    
            // This is a normal string entry
            if ( typeof root === 'string' ) {
                id = root;
                li = $('<li></li>').html('<a href="' + id  + '">' + root +  '</a>');
                parentEl.append(li);
            }
    
            // Or this is an object 
            else {
                // Loop over all the keys
                Object.keys(root).forEach(function(child) {
                    id = removeSpecialChars(child);
                    istopmenu = parentEl.hasClass('navbar-nav');
                    li = $('<li class="dropdown' + (istopmenu ? '' : ' dropdown-submenu') + '"></li>').html('<a class="dropdown-toggle" data-toggle="dropdown"  href="#" onclick="javascript:createView(\'' + id +  '\');" aria-expanded="false">' + child + (istopmenu ? '<span class="caret"></span>' : '') + '</a>');
                    var ul = $('<ul class="dropdown-menu" role="menu"></ul>');
    
    
                    // Recursively loop over the array elements 
                    buildMenu(root[child], ul);
                    li.append(ul);
                    parentEl.append(li);
                 });
            }
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2017-03-03
      • 2023-03-26
      • 2013-03-21
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      相关资源
      最近更新 更多