У меня есть веб-страница, на которой я хотел бы динамически отображать дерево на основе массива JSON с помощью jQuery. Каждый узел моего дерева имеет флажок, связанный с ним. Когда я нажимаю на узел, у которого есть дочерние элементы, я хотел бы, чтобы все они были проверены. Я уже позаботился о печати дерева и флажков, и сейчас я пытаюсь выбрать дочерние узлы, и я не могу.
Ниже приведен код (упрощенный), который у меня есть. У кого-нибудь есть идеи, как я могу автоматически устанавливать флажки для детей, когда флажок установлен с помощью jQuery?
Спасибо!
<html>
<head>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var myJSON = {
"d": {
"__type": "Branch",
"Name": "$",
"FullPath": "$\\$",
"SubBranch": [
{
"__type": "Branch",
"Name": "System",
"FullPath": "$\\System",
"SubBranch": [
{
"__type": "Branch",
"Name": "Library",
"FullPath": "$\\System\\Library",
"SubBranch": [
]
},
{
"__type": "Branch",
"Name": "Configuration",
"FullPath": "$\\System\\Configuration",
"SubBranch": [
{
"__type": "Branch",
"Name": "Reimage",
"FullPath": "$\\System\\Configuration\\Reimage",
"SubBranch": [
]
},
{
"__type": "Branch",
"Name": "Installation",
"FullPath": "$\\System\\Configuration\\Installation",
"SubBranch": [
]
}
]
},
]
}
]
}
}
var output;
var indentationLevel = 0;
function GetSpacing(numberOfSpaces) {
var tabs = '';
for (i = 0; i < numberOfSpaces; i++) {
tabs += ' ';
}
return tabs;
}
function GetHtmlForFeaturePath(featurePath) {
return '<div>' + GetSpacing(indentationLevel) + '<input type="checkbox" id="' + featurePath.FullPath + '" class="featureTreeCheckbox" />' + featurePath.Name + "</div>";
}
function GetHtmlForFeaturePaths(node) {
output += GetHtmlForFeaturePath(node);
indentationLevel++;
jQuery.each(node.SubBranch, function() {
GetHtmlForFeaturePaths(this);
});
indentationLevel--;
}
String.prototype.startsWith = function(str) {
return this.match("^" + str) == str;
}
window.onload = function() {
GetHtmlForFeaturePaths(myJSON.d);
document.writeln(output);
/* How do I tell a node to check its children? */
$('input').click(function(event) {
var clickedControlId = this.id;
alert(clickedControlId);
/* alert($.grep(myJSON.d, function (a) { return a.FullPath == clickedControlId })); */
});
}
</script>
</head>
<body>
<a href="http://jquery.com/">jQuery</a>
</body>
</html>