user2560521
user2560521

Reputation: 476

how to build a dynamic menu using jquery?

I try to create a dynamic menu using jquery:

  function createMenu(array) {
            var main = $("#mainUl");
            for (var i = 0; i < array.length; i++) {          
                main.append("<li>");
                $('li').append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>");
                main.append("</li>");
            }    
        }

The menu is created, but in each li i get more than one span, there is an "inside" loop (I think...) createing more spans than needed... how can i solve/control it so each li gets one span according to the for - loop index ?

Upvotes: 0

Views: 2460

Answers (3)

Mattos
Mattos

Reputation: 809

$('li') this selector will get every li on the html so every time you iterate to create a new li element you gonna add a new span to all of them.

Try like this:

function createMenu(array) {
        var main = $("#mainUl");
        for (var i = 0; i < array.length; i++) { 
            var menuLine = $('<li>');
            menuLine.html("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + " </span></a>" );                                
            main.append(menuLine);
        }    
    }

Upvotes: 0

AOZ
AOZ

Reputation: 196

you can do it simply as below

  function createMenu(array) {
                var main = $("#mainUl");
                for (var i = 0; i < array.length; i++) {          
                    main.append($("<li>").append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>"));
                }    
            }

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You are seeing that behaviour because you are appending that anchor with span in selecting all the li elements.

Try,

function createMenu(array) {
    var main = $("#mainUl");
    for (var i = 0; i < array.length; i++) {          
      var xLi =("<li>").appendTo(main);
      xLi.append("<a href='#" + myArray[i].id + "'><span>" + myArray[i].id + "</span></a>");
      main.append(xLi);
    }    
}

Upvotes: 1

Related Questions