首页 > Web开发 > 详细

如何用 js 递归输出树型

时间:2015-09-06 23:03:45      阅读:216      评论:0      收藏:0      [点我收藏+]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>

    <script>

        var data = [
            { id: 1, title: a, pid: 0 },
            { id: 2, title: a1, pid: 1 },
            { id: 3, title: a11, pid: 2 },
            { id: 4, title: a12, pid: 2 },
            { id: 5, title: a2, pid: 1 },
            { id: 6, title: a21, pid: 5 }
        ];
        function fn(data, pid) {
            var result = [], temp;
            for (var i in data) {
                if (data[i].pid == pid) {
                    result.push(data[i]);
                    temp = fn(data, data[i].id);
                    if (temp.length > 0) {
                        data[i].children = temp;
                    }
                }
            }
            return result;
        }
        //console.log(fn(data, 0));


        Array.prototype.ToTreeJson = function (pid) {
            var result = [], temp;
            for (var i in this) {
                if (this[i].pid == pid) {
                    result.push(this[i]);
                    temp = fn(this, this[i].id);
                    if (temp.length > 0) {
                        this[i].children = temp;
                    }
                }
            }
            return result;
        }

        var p = data.ToTreeJson(0);
    </script>
</body>
</html>

 

如何用 js 递归输出树型

原文:http://www.cnblogs.com/yeminglong/p/4787533.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!