没有根节点,那么构建DOM树和初始化treegrid的过程也需要做出相应的调整,帮我修改代码:// 根节点ID和名称 var rootId = "N000"; var rootName = "菜单"; // 获取指定节点下的所有子节点 function getChildren(nodes, id) { var result = []; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; if (node.parentIndex === id) { node.children = getChildren(nodes, node.id); result.push(node); } } return result; } // 构建 DOM 树 function buildTree(parentNode, children) { for (var i = 0; i < children.length; i++) { var childNode = children[i]; var tr = $('<tr class="treegrid-' + childNode.id + '"><td>' + childNode.name + '</td></tr>'); parentNode.append(tr); if (childNode.children && childNode.children.length > 0) { var subTable = $('<table></table>'); tr.append(subTable); buildTree($('<tbody></tbody>').appendTo(subTable), childNode.children); } } } // 主程序 const username = 'hzx'; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.status == 200) { var jsonData = JSON.parse(xhr.responseText); var root = { id: rootId, name: rootName, children: getChildren(jsonData, rootId) }; buildTree($('#tree tbody'), root.children); // 初始化 treegrid $('#tree').treegrid({ expanderExpandedClass: 'glyphicon glyphicon-minus', expanderCollapsedClass: 'glyphicon glyphicon-plus' }); } else { alert("请求失败:" + xhr.statusText); } } }; xhr.open("GET", "shouquan.php?username=" + username, true); xhr.send();
时间: 2023-12-06 17:41:12 浏览: 74
修改的代码如下:
// 根节点ID和名称
var rootId = "N000";
var rootName = "菜单";
// 获取指定节点下的所有子节点
function getChildren(nodes, id) {
var result = [];
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.parentIndex === id) {
node.children = getChildren(nodes, node.id);
result.push(node);
}
}
return result;
}
// 构建 DOM 树
function buildTree(parentNode, children) {
for (var i = 0; i < children.length; i++) {
var childNode = children[i];
var tr = $('<tr class="treegrid-' + childNode.id + '"><td>' + childNode.name + '</td></tr>');
parentNode.append(tr);
if (childNode.children && childNode.children.length > 0) {
var subTable = $('<table></table>');
tr.append(subTable);
buildTree($('<tbody></tbody>').appendTo(subTable), childNode.children);
}
}
}
// 主程序
const username = 'hzx';
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
var root = { id: rootId, name: rootName, children: getChildren(jsonData, rootId) };
var tbody = $('<tbody></tbody>');
buildTree(tbody, root.children);
$('#tree').append(tbody);
// 初始化 treegrid
$('#tree').treegrid({
expanderExpandedClass: 'glyphicon glyphicon-minus',
expanderCollapsedClass: 'glyphicon glyphicon-plus'
});
} else {
alert("请求失败:" + xhr.statusText);
}
}
};
xhr.open("GET", "shouquan.php?username=" + username, true);
xhr.send();
主要修改如下:
1. 将构建的 DOM 树添加到 tbody 中,最后再添加到 #tree 中。
2. 初始化 treegrid 的代码不变,因为 treegrid 是根据 class 来进行初始化的,而不是根据 DOM 树结构。
阅读全文