递归无限级树下拉菜单

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

效果图:


	/**
	  *树形菜单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("加载栏目出错!");
		}
	});
	
});
 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值