项目中需要用到无限级树型下拉菜单,花时间折腾了一下。在此记录下来以备后用!
效果图:

/**
*树形菜单VO
*/
public class SelectTree implements Serializable{
private int id;
private String name;
private List<SelectTree> child = new ArrayList<SelectTree>();
//getter & setter ....略
}
代码片段:
/**
* 构建树型菜单数据
*/
public List<SelectTree> buildNode(int pid,List<YcChannel> channels){
List<SelectTree> result = new ArrayList<SelectTree>();
for(YcChannel chl:channels){
SelectTree node = new SelectTree();
if(null != chl.getParentId() && chl.getParentId().equals(pid)){
node.setId(chl.getChannelId());
node.setName(chl.getName());
List<SelectTree> children = buildNode(chl.getChannelId(),channels);
if(null != children && 0 < children.size()){
node.setChild(children);
}
result.add(node);
}
}
return result;
}
public String queryChannelList() {
ycChannelList = this.channelSer.queryChannelList();
List<SelectTree> trees = new ArrayList<SelectTree>();
for(YcChannel yc:ycChannelList){
if(null == yc.getParentId()){
SelectTree t = new SelectTree();
t.setId(yc.getChannelId());
t.setName(yc.getName());
t.setChild(buildNode(t.getId(),ycChannelList));
trees.add(t);
}
}
this.setAjaxData(trees);
return AJAX_DATA;
}
前端JS代码:
//recursive tree node
function buildNode(len,data){
var prefix = "|";
for(var i=0;i<len;i++){
prefix += "-";
}
$.each(data,function(i,item){
if(0 < item.child.length){
$('#typeid').append("<option value="+item.id +">" + prefix + item.name + "</option>");
buildNode(len+1,item.child);
}else{
$('#typeid').append("<option value="+item.id +">" + prefix + item.name + "</option>");
}
});
}
$.ajax({
url:'${base}/channel/channelAction!queryChannelList.action',
type:'GET',
dataType:'json',
contentType:'application/json',
success:function(json){
if(json.success){
$('#typeid').empty();
$('#typeid').append("<option value='0'>请选择栏目...</option>");
$.each(json.data,function(i,item){
if(null == item.parentId){
$('#typeid').append("<option value="+item.id +">" + item.name + "</option>");
buildNode(1,item.child);
}
});
}
},
error:function(){
alert("加载栏目出错!");
}
});
});
616

被折叠的 条评论
为什么被折叠?



