数据格式:
var data = [
{title: "11111",childs : [
{title:"aaaaa", childs:[
{title: "xg"}
]},
{title:"bbbbb"}
]
},
{title: "22222",childs : [
{title:"aaaaa"},
{title:"bbbbb"}
]
}
];
递归函数:
function menu(data){
var ul = "<ul>";
for(var i = 0; i < data.length; i++){
ul+="<li><a>"+data[i].title+"</a>";
if(data[i].childs){ul+=argument.callee(data[i].childs);}
ul+="</li>";
};
ul+="</ul>";
return ul;
}
调用:
var menu = menu(data);
结果:
也可以做成jq插件
var Menu = function(el,opt){
this.el = el;
//this.default = {}, // 插件默认参数,在这里不需要
this.opt = opt;
// this.opt = $.extend({},this.default,opt); // 插件默认参数和传参合并,在这里不需要
};
Menu.prototype = {
init: function(){
var opt = this.opt;
var ul = this.create(opt);
this.el.append(ul);
},
create: function(opt){
var ul = ‘<ul>‘;
for(var i = 0; i < opt.length; i++){
ul += ‘<li>‘+opt[i].title;
if(opt[i].childred && opt[i].children != ‘undefined‘){
ul += arguments.callee(opt[i].childred)
}
ul += ‘</li>‘;
};
ul += ‘</ul>‘;
return ul;
}
}
$.fn.menu = function(opt){
// 这里的this是指$(select);
var menu = new Menu(this, opt);
return menu.init();
}
调用: $(select).menu(data);