码迷,mamicode.com
首页 > Web开发 > 详细

如何用 js 递归输出树型

时间:2015-09-06 23:04:04      阅读:380      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!