0

Ok what I am trying to do is create a dynamic menu based on an array First dimesion elements will be top level and Second dimension levels will be sub items of said parent how will I do this?

$(document).ready(function(e) {
//var maxLevels = 3;//Max Levels Of The List TO Traverse

var nav = new Array();
nav[0] = "Item A";
nav[0][0] = "Item AB"; 
nav[1] = "Item B";
nav[1][0] = "Item BA";

var menu = "";
nav.forEach(function(e) {
    menu += "<li>" + e + "</li>";
});


$('#info').html(menu);


});

4 Answers 4

3

Having declared your array nav you can access its elements with nav[index] but you can't add a second dimension to item 0 just by saying nav[0][0] - you need to declare nav[0] as an array before using it:

nav[0] = [];
nav[0][0] = ...

But you can declare it all in one statement with an array literal, where for your purpose I'd suggest an array of objects:

var nav = [
    { "title" : "Item A",
      "submenu" : [ "Item A1", "Item A2" ] },
    { "title" : "Item B",
      "submenu" : [ "Item B1", "Item B2", "Item B3"] }
];

If your desired output was this:

<ul>
   <li>Item A
       <ul>
           <li>Item A1</li>
           <li>Item A2</li>
       </ul>
   </li>
   <li>Item B
       <ul>
           <li>Item B1</li>
           <li>Item B2</li>
           <li>Item B3</li>
       </ul>
   </li>
</ul>

You could do it like so:

var $menu = $("<ul></ul>");
$.each(nav, function(i, val) {
    var $item = $("<li></li>").html(val.title),
        $sub = $("<ul></ul>");
    $.each(val.submenu, function(j, sub) {
        $sub.append($("<li></li>").html(sub));
    });
    $menu.append($item.append($sub));    
});
$("body").append($menu);

Demo: http://jsfiddle.net/9kRs3/

Of course you could build the menu up as a string like in your original code, but I've chosen to create the elements as I go.

Using the object structure above you can easily add some extra properties to define what happens when each item is clicked. And you could make each item in the submenu arrays have the same object structure as the top level so that you can nest more and more levels as needed.

Sign up to request clarification or add additional context in comments.

Comments

1

The way you're trying to build your hierarchy will not work (as nnnnnn already explained).

You could try something like this, which will work for any number of levels:

var nav = [{
    label: 'Item A',
    children: [{
        label: 'Item AB',
        children: []
    }]
}, {
    label: 'Item B',
    children: [{
        label: 'Item BA',
        children: []
    }]
}​]​;

​var menu = [];

(function build(elements) {
   menu.push('<ul>');
   $.each(elements, function (i, val) {
     menu.push('<li>', val.label);
     build(val.children);
     menu.push('</li>');
   });
   menu.push('</ul>');
}(nav));

$('#info').html(menu.join(''));

​demo: http://jsfiddle.net/jw3zm/

Comments

1

I'm not sure an array is the best way. You could use a mix of arrays and object instead, it'll be easier IMO. This will work for one submenu, but can be extended... http://jsfiddle.net/elclanrs/Tp4KM/

var menu = {
    about: ['one', 'two', 'three'],
    contact: ['four', 'five']
};

var items = '';

for (var m in menu) {
    items +=
        '<ul class="menu">' +
            '<li><a href="#">' + m + '</a>' +                
                '<ul>' +
                    '<li><a href="#">' +
                    menu[m].join('</a></li><li><a href="#">') +
                    '</a></li>' +
                '</ul>' +
            '</li>' +
        '</ul>';
}

$('body').append(items);

Comments

0

I use javascript from Yoshi and here you can see my HTML code. Problem is that my website is blank and doesn't show list. I don't understand why it's not running because code doesn't show errors.

    <!DOCTYPE html>
<html>
    <head>
    <meta charset="UTF-8">
    <title>Menu</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>
    </head>
<body>
    <div id="info"></div>
</body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.