I've been fooling around with a very minimalistic jquery admin area menu. The thing is 开发者_如何学PythonI 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
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);
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);
精彩评论