官方文档: [url]http://www.trirand.com/jqgridwiki/doku.php?id=wiki:treegrid[/url]

[color=red][b]问题和注意[/b][/color]:
1. 如果grid的参数存在"rownumbers": true, "rownumWidth": 20,那么无法在正确的位置显示ExpandColumn信息,他会显示在ExpandColumn的前一列。所以应该动态计算并放到下一列。可能会引起setTreeRow方法的错误,因为这个方法是使用真实的ExpandColumn。
2. jsonReader: {
root: "dataRows", //[color=darkblue]设定这个参数,有时候也无法正常现实[/color]
repeatitems : false //[color=darkblue]不需要再去后台刷新,否则可能有问题,所以最好第一次就加载所有数据[/color]
}
3. gridview, boolean 设置为true将提高5~10倍的显示速度。但不能再使用treeGrid, subGrid, 或afterInsertRow事件
4. 如果getNodeParent方法无效,可能是因为你给的recorddata.parentId的类型不对,这里需要recorddata.parentId是字符串,才能找到的.
5. collapseNode和collapseRow,expandNode和expandRow一般是成对调用。
6. 移动一个节点以及它的子节点。要字节加方法,才能实现,其实它至此的treegrid功能很弱,一些东西要自己实现,后面附加一些自己实现的方法


第一个列子
/pages/demo/tree.json
----------------------------------

{
    "total":11,
    "page":1,
    "records":11,
    "rows":[
        {"id":1, "name":"Pandy1", "cell":["第一级1",0,null,false,false]},
        {"id":3, "name":"Pandy2", "cell":["第二级1",1,1,true,false]},
        {"id":2, "name":"Pandy3", "cell":["第一级2",0,null,true,false]}
    ]
}



<%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
<%@ include file="/common/taglibs.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Insert title here</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" src="<c:url value="/pages/org/grid.treegrid.js"/>"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#treegrid").jqGrid({
                treeGrid: true,
                treeGridModel: 'adjacency',
                ExpandColumn: 'name',
                ExpandColClick: true,
                url: '/pages/demo/tree.json',
                datatype: 'json',
                colNames: ["管理选项"],
                colModel: [
                    { name: 'name', index: 'name' }
                ],
                pager: "false",
                height: 'auto',
                width: '210',
                viewrecords: true,
                //   caption: 'none',
                jsonReader: {
                    root: "rows",
                    total: "total",
                    repeatitems: true
                }

            });
        })
        ;
    </script>

</head>
<body>
<table id="treegrid"></table>
<div id="ptreegrid"></div>
</body>
</html>




第二个例子


[
    {"id":0,"username":"王三1","level":0,"address":"USA","isLeaf":false,"age":20,"expanded":true,"password":"123"},
    {"id":1,"username":"王三2","level":1,"address":"USA","isLeaf":false,"age":21,"parent":0,"expanded":true,"password":"123"},
    {"id":2,"username":"王三3","level":2,"address":"USA","isLeaf":true,"age":22,"parent":1,"expanded":true,"password":"123"}
]



<%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8" %>
<%@ include file="/common/taglibs.jsp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Insert title here</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <script type="text/javascript" src="<c:url value="/pages/org/grid.treegrid.js"/>"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            jQuery("#treegrid").jqGrid({
                treeGrid: true,
                treeGridModel: 'adjacency', //treeGrid模式,跟json元数据有关 ,adjacency/nested
                ExpandColumn : 'username',
                scroll: "true",
                url: '/pages/demo/tree1.json',
                datatype: 'json',
                colNames:['编号','姓名','密码','年龄','地址','出生日期'],
                colModel:[
                    {name:'id',index:'id', width:90,sorttype:"int"},
                    {name:'username',index:'username', width:110,sorttype:"int"},
                    {name:'password',index:'password', width:80},
                    {name:'age',index:'age', width:80},
                    {name:'address',index:'address', width:80},
                    {name:'time',index:'time', width:80,sorttype:"date"}
                ],
                pager: "false",
                sortname: 'id',
                sortorder: "desc",

                jsonReader: {
                    root: "dataRows",
                    repeatitems : false
                },
                treeReader : {
                    level_field: "level",
                    parent_id_field: "parent",
                    leaf_field: "isLeaf",
                    expanded_field: "expanded"
                },
                caption: "jqGrid test",
                mtype: "POST",
                height: "auto",    // 设为具体数值则会根据实际记录数出现垂直滚动条
                rowNum : "-1",     // 显示全部记录
                shrinkToFit:false  // 控制水平滚动条
            });
        });
    </script>

</head>
<body>
<table id="treegrid"></table>
</body>
</html>




[color=blue][b]一些自己实现的方法[/b][/color]


/* 以下是常用的方法 */
        /**
         * 设定默认关闭的等级,同时自动关闭它的下一级
         * 这里递归,出现错误
         * @param GridConfig
         * @param level
         */
        /* --------------------------- tree grid for jqGrid ------------------------------- */
        setDefaultOpenLevel: function (GridConfig, level) {
            var childRows = $("#" + GridConfig.divId).jqGrid('getRootNodes');
            for (var i = 0; i < childRows.length; i++) {
                var rows = $("#" + GridConfig.divId).jqGrid('getNodeChildren', childRows[0]);
                for (var m = 0; m < rows.length; m++) {
                    if (rows[m].level <= level) {
                        $("#" + GridConfig.divId).jqGrid('collapseNode', rows[m]);
                        $("#" + GridConfig.divId).jqGrid('collapseRow', rows[m]);
                    }

                    //遍历导致浏览器崩溃,所以多做一次循环,进入深一层继续关闭就好.
                    var trows = $("#" + GridConfig.divId).jqGrid('getNodeChildren', rows[m]);
                    for (var k = 0; k < trows.length; k++) {
                        if (trows[k].level <= (level + 1)) {
                            $("#" + GridConfig.divId).jqGrid('collapseNode', trows[k]);
                            $("#" + GridConfig.divId).jqGrid('collapseRow', trows[k]);
                        }
                    }
                }
            }
        },
        /**
         * 展开某个节点的所有父节点
         * @param GridConfig
         * @param id
         */
        openParentsNode: function (GridConfig, rowid) {
            var currNode = $.GridUtils.getCurrentNode(GridConfig, rowid);
            currNode.parentId=""+currNode.parentId;
            var parent = $("#" + GridConfig.divId).jqGrid('getNodeParent', currNode);
            if (parent != null) {
                $("#" + GridConfig.divId).jqGrid('expandNode', parent);
                $("#" + GridConfig.divId).jqGrid('expandRow', parent);
                $.GridUtils.openParentsNode(GridConfig, parent.id);
            }
        },
        getAllChildrenNodes: function (GridConfig, root, level, treeList) {
            if (typeof treeList == "undefined") {
                treeList = [];
            }
            var chs = $("#" + GridConfig.divId).jqGrid('getNodeChildren', root);
            treeList[treeList.length] = root;

            if (chs != null && chs.length > 0) {
                for (var i = 0; i < chs.length; i++) {
                    $.GridUtils.getAllChildrenNodes(GridConfig, chs[i], level + 1, treeList);
                }
            }
            return treeList;
        },
        /**
         * 自己实现获得父节点方法
         * @param GridConfig
         * @param rowid
         * @returns {*}
         */
        getNodeParent: function (GridConfig, rowid) {
            var roots = $("#" + GridConfig.divId).jqGrid('getRootNodes');
            var row = $.GridUtils.getRowData(GridConfig, rowid);

            for (var i = 0; i < roots.length; i++) {
                var treeList = $.GridUtils.getAllChildrenNodes(GridConfig, roots[i], 0);
                for (j = 0; j < treeList.length; j++) {
                    if (treeList[j].id == row.parentId) {
                        return  treeList[j]
                    }
                }
            }

            return null;
        },
        /**
         * 自己实现获得当前节点方法
         * @param GridConfig
         * @param rowid
         * @returns {*}
         */
        getCurrentNode: function (GridConfig, rowid) {
            var roots = $("#" + GridConfig.divId).jqGrid('getRootNodes');
            var row = $.GridUtils.getRowData(GridConfig, rowid);

            for (var i = 0; i < roots.length; i++) {
                var treeList = $.GridUtils.getAllChildrenNodes(GridConfig, roots[i], 0);
                for (j = 0; j < treeList.length; j++) {
                    if (treeList[j].id == row.id) {
                        return  treeList[j]
                    }
                }
            }

            return null;
        },
        /**
         * 第一个节点是当前节点,第二个以及后面的,属于它的子节点
         * @param GridConfig
         * @param rowid
         * @returns {*}
         */
        getAllChildrenNodesByRowId: function (GridConfig, rowid) {
            var row = $.GridUtils.getRowData(GridConfig, rowid);
            row._id_ = row.id;
            var rowList = $.GridUtils.getAllChildrenNodes(GridConfig, row, row.level);
            if (rowList == null || rowList.length == 0)
                return rowList;

            if (rowList != null && rowList.length > 0) {
                //替换当前节点
                rowList[0] = $.GridUtils.getCurrentNode(GridConfig, rowid);
            }
            return rowList;

        },
        /**
         * 自己实现的删除节点以及子节点,注意,先从叶子删除
         * @param GridConfig
         * @param rowid
         */
        deleteTreeNodeAndChildren: function (GridConfig, rowid) {
            var treeList = $.GridUtils.getAllChildrenNodesByRowId(GridConfig, rowid);
            //先删除子节点再删除当前节点
            for (var i = treeList.length - 1; i >= 0; i--) {
                if (treeList[i] != null)
                    $("#" + GridConfig.divId).jqGrid('delTreeNode', treeList[i].id);
            }
        },
        /**
         * 移动一个节点到另一个节点
         * @param GridConfig
         * @param newNodeData
         */
        moveTreeNode: function (GridConfig, newNodeData) {
            if (typeof(newNodeData.parentId) == "undefined") {
                alert("没有设定父节点ID");
                return;
            }
            var levelPad = 0;  //用于校对心节点的level
            var rowid = typeof(newNodeData.rowid) == "undefined" ? newNodeData.id : newNodeData.rowid;
            var newParentId = newNodeData.parentId;
            var newParent;
            var oldParent;
            //获得之前的当前节点以及所有子节点
            var treeList = $.GridUtils.getAllChildrenNodesByRowId(GridConfig, rowid);
            //alert("treeList=" + $.toJSON(treeList));
            if (treeList != null && treeList.length > 0) {
                newParent = $.GridUtils.getCurrentNode(GridConfig, newParentId);
                oldParent = $.GridUtils.getCurrentNode(GridConfig, treeList[0].parentId);
                //新旧的父节点的level差量
                if (newParent != null) {
                    //levelPad = newParent.level - treeList[0].level;
                    levelPad = newParent.level - oldParent.level;
                }
                //alert("newParent="+ $.toJSON(newParent));
                //alert("oldParent="+ $.toJSON(oldParent));
                //alert("levelPad="+ levelPad);
            }

            //删除当前节点以及所有子节点
            $.GridUtils.deleteTreeNodeAndChildren(GridConfig, rowid);
            //alert("deleteTreeNodeAndChildren");

            //更新当前节点的业务信息
            treeList[0] = $.extend(treeList[0], newNodeData);

            for (var i = 0; i < treeList.length; i++) {
                treeList[i]._id_ = treeList[i].id;
                treeList[i].loaded = true;
                //新旧的父节点的level差量 + 1,就是当前节点应该的level
                treeList[i].level = treeList[i].level + levelPad;
                //alert("treeList[i]=" + $.toJSON(treeList[i]));
                $("#" + GridConfig.divId).jqGrid('addChildNode', treeList[i].id, treeList[i].parentId, treeList[i]);
            }
            $.GridUtils.openParentsNode(GridConfig, treeList[0].id);

            //return;

            //旧的父节点不存在子节点的时候,无法隐藏图标,另求其他方法
            //重新检查旧的父节点,当旧的父节点已经不存在子节点的时候,应该重新读取,删除,再加入,保证图标隐藏。
            treeList = $.GridUtils.getAllChildrenNodesByRowId(GridConfig, oldParent.id);
            if (treeList != null && treeList.length == 1) {
                $.GridUtils.deleteTreeNodeAndChildren(GridConfig, treeList[0].id);
                treeList[0]._id_ = oldParent.id;
                treeList[0].loaded = true;
                treeList[0].isLeaf = true;
                //alert("treeList[0]=" + $.toJSON(treeList[0]));
                $("#" + GridConfig.divId).jqGrid('addChildNode', treeList[0].id, treeList[0].parentId, treeList[0]);
            }

        }