欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js递归数据处理

程序员文章站 2022-05-18 20:52:16
...
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
		</script>
	</head>

	<body>
		<div id="div_menu"></div>
	</body>

</html>
<script type="text/javascript">
	var data = {
		"child": [{
				"id": "M001",
				"name": "一级",
				"href": "#",
				"child": ""
			},
			{
				"id": "M002",
				"name": "一级",
				"href": "#",
				"child": [{
						"id": "M003",
						"name": "二级",
						"href": "#",
						"child": [{
								"id": "M006",
								"name": "三级",
								"href": "#",
								"child": ""
							},
							{
								"id": "M007",
								"name": "三级",
								"href": "#",
								"child": ""
							}
						]
					},
					{
						"id": "M004",
						"name": "二级",
						"href": "#",
						"child": ""
					},
					{
						"id": "M005",
						"name": "二级",
						"href": "#",
						"child": ""
					}
				]
			},
			{
				"id": "M006",
				"name": "一级",
				"href": "#",
				"child": [{
					"id": "M005",
					"name": "二级",
					"href": "#",
					"child": ""
				}]
			}
		]
	};
	$(function() {
		var showlist = $("<ul></ul>");
		showallChild(data.child, showlist);
		$("#div_menu").append(showlist);
	});

	//递归函数
	function showallChild(data_list, parent) {
		for(var datas in data_list) {
			//如果有子节点,则遍历该子节点
			if(data_list[datas].child.length > 0) {

				//逻辑处理
				var li = $("<li></li>");
				$(li).append(data_list[datas].name).append("<ul></ul>").appendTo(parent);

				//递归
				showallChild(data_list[datas].child, $(li).children().eq(0));
			}
			//如果该节点没有子节点,则直接将该节点li以及文本创建好直接添加到父亲节点中
			else {

				$("<li></li>").append(data_list[datas].name).appendTo(parent);
			}
		}
	}
</script>

相关标签: recursion