我有一个带有树状数据的 json 对象。我想以交互方式在 UI 上显示它。单击组件时,应显示其子组件,依此类推。我写了以下代码
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.js"></script>
</head>
<body>
<div>
<ul id="result"></ul>
</div>
<script>
var json_data = {
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 2,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 1,
"children": []
}
]
}
]
};
$(document).ready($(function(){
var $result = $('#result');
start(json_data )
//Root Node display
function start(obj)
{
$('<li id="' + obj.component + '">').text(obj.component + '-'+obj.status).appendTo($result);
$("#"+obj.component).click(function(){
displaychildren(obj);
});
}
Display the children of an element on click by recursion
function displaychildren(node)
{
$.each(node.children,function (i,v){
$('<li id="' + v.component + '">').text(v.component + '-'+v.status).appendTo($result);
if$("#"+v.component).click(function(){
alert("Problem is here");
displaychildren(v);
});
});
}
});
我面临的问题是 displaychildren 函数中元素的 onclick 不起作用。如果删除了 onclick 条件,则所有组件的所有元素都将被显示。我希望仅显示所选组件的子项。有谁知道是什么导致了这个问题