Hi I want to create a html structure like this:
<ul class="menu">
<li class="top"><a></a></li>
<li><a class="button1"></a></li>
<li class="extend">
<a class="button 1"></a>
<ul>
<li class="last"><a class="button2"></a></li>
</ul>
</li>
<li class="extend">
<a class="button1"></a>
<ul>
<li><a class="button2"></a></li>
<li><a class="button3"></a></li>
<li class="last"><a class="button4"></a></li>
</ul>
</li>
<li><a class="button1"></a></li>
<li class="last"><a class="button2"></a></li>
</ul>
with this code:
$(document).ready(function(){
var menuArray = [
{
'name':'main 1',
'className':'main_1'
},{
'name':'main 2',
'group':'group1'
},{
'name':'main 3',
'group':'group1',
},{
'name':'main 4',
'group':'group2'
},{
'name':'main5',
'group':'group2'
},{
'name':'button'
}
];
var createMenu = function(toolArray){
var menu = $('<ul class="menu"><li class="top"><a></a></li></ul>').appendTo('body');
var groupArray = [];
$.each(toolArray, function(index, value){
var group = value.group || '';
var name = value.name || '';
var elementClass = value.className || '';
if(typeof(value.group) === 'undefined'){
console.log('crete button - no group');
var li = $('<li><a class="'+name+'">'+name+'</a></li>');
li.click(value.onClick);
menu.append(li);
}
else{
if(typeof(groupArray[group]) === 'undefined'){//first element in group
console.log('create first element in group '+group);
groupArray[group] = 1;
var li = $('<li class="'+group+'"><a class="'+elementClass+'">'+name+'</a></li>');
menu.append(li);
}
else{
if(groupArray[group] > 1){//third, ... element in group
var li = $('<li><a class="'+elementClass+'">'+name+'</a></li>');
$('li.'+group+' ul', menu).append(li);
}
else{//second element in group
var li_parent = $('li.'+group, menu).addClass('extend');
var ul = $('<ul><li class="'+group+'"><a class="'+elementClass+'">'+name+'</a></li></ul>');
$(ul).append(li_parent);
}
groupArray[value.group] = groupArray[value.group]+1;
}
}
});
};
createMenu(menuArray);
});
The problem is, that the code only shows this:
<ul class="menu">
<li class="top"><a></a></li>
<li><a class="main 1">main 1</a></li>
<li><a class="button">button</a></li>
</ul>
Any idea why? http://jsfiddle.net/W4Phv/