views:

42

answers:

2

I've been fooling around with a very minimalistic jquery admin area menu. The thing is I want jQuery to build 3 equal menus with different ID's. I managed to do this by creating a function and call it 3 times with different variables, but I'd like to ask my first question on this lovely community:

What is the most minimalistic and efficient way of creating 3 elements with different IDs and content?

d=['Varer','Kate','Produ','Tilbud','Sider','Info','Pref'];

e=['Varer1','Kate1','Produ1','Tilbud1','Sider1','Info1','Pref1'];

f=['Varer2','Kate2','Produ2','Tilbud2','Sider2','Info2','Pref2'];

function menu(){
var e='';
$.each(d,function(a,b){e+='<a href=#'+b+'>'+b+'</a>'});
$('body').append('<div id=c>'+e+'</div>');}
menu();

Thanks in advance

A: 

How about this: http://jsfiddle.net/M6Upv/

d = ['Varer', 'Kate', 'Produ', 'Tilbud', 'Sider', 'Info', 'Pref'];
e = ['Varer1', 'Kate1', 'Produ1', 'Tilbud1', 'Sider1', 'Info1', 'Pref1'];
f = ['Varer2', 'Kate2', 'Produ2', 'Tilbud2', 'Sider2', 'Info2', 'Pref2'];

function menu(i, array) {
    var e = '';
    $.each(array, function(a, b) { e += '<a href=#' + b + '>' + b + '</a>'; });
        // Use the "i" value to make sure the container ID is unique
    $('body').append('<div id=c' + i + '>' + e + '</div>');
}
   // Place your arrays in an array, and call a separate .each()
   //    with your menu() function as the callback.
$.each([d, e, f], menu);​
patrick dw
That was an awesome website, thanks for the link and the help.
Ulrik M
@Ulrik M - I hope I understood your question. Seemed like you were trying to avoid multiple calls to your `menu()` function. Also, don't forget to "accept" an answer by clicking the checkmark to the left of the one that was most helpful.
patrick dw
+2  A: 

Your method is actually really good. Keep in mind these following issues though:

Missing the var keyword will make the variable global.

var d = ['Varer' ..];

Keep the function independent of the outside environment. Pass the array as a parameter.

function menu(array) {

}

Pass the id as an argument into the function which currently seems to assign all divs the id "c".

function menu(id, dataArray) {

}

Each time you append something to a string, a new string is created. A faster method is to add these strings to an array and join them at the end. Here's the menu function keeping all above points in mind.

function menu(id, data) {
    var links = $.map(data, function(value) {
        return  '<a href="#' + value + '">' + value + '</a>';
    }).get();

    var div = $('<div>', { 
        id: id,
        html: links.join('')
    });
    $('body').append(div);
}

Minimalistic code does not mean you should use one letter variable names. Leave that to the minifier.

menu('firstId', d);
menu('secondId', e);
menu('thirdId', f);
Anurag
Thanks for the quick reply, really appreciated.
Ulrik M