[英]why does $.each makes array object undefined, but for loop works
I am attempting to iterate through a tree structure. 我试图迭代树结构。 The tree is an array of JSON objects.
树是JSON对象的数组。 If I iterate in a for loop all is fine...but if I iterate using $.each the iterated object becomes undefined.
如果我在for循环中迭代一切都很好......但是如果我使用$ .each迭代,则迭代对象变为未定义。 Any help understanding this would be great.
任何帮助理解这将是伟大的。
HTML - same for both HTML - 两者都相同
<ul id="treeList" class="list-group" style="margin: 0 auto; list-style-type: none;"></ul>
Code - working version 代码 - 工作版
var tree = [{
"name": "Parent 1",
"subcat": []
},
{
"name": "Parent 2",
"subcat": [{
"name": "child 2",
"subcat": [{
"name": "grandchild 2",
"subcat": []
}]
}]
},
{
"name": "Parent 3",
"subcat": []
}
];
buildTree($('#treeList'), tree);
function buildTree($list, nodes) {
for (var i = 0, len = nodes.length; i < len; i++) {
var $item = $('<li><a href="#">' + nodes[i].name + '</a></li>');
if (nodes[i].subcat.length) {
var $subList = $('<ul></ul>');
$item.append($subList);
buildTree($subList, nodes[i].subcat);
}
$list.append($item);
}
}
Fiddle: https://jsfiddle.net/number40/0vpusefr/ 小提琴: https : //jsfiddle.net/number40/0vpusefr/
Code - not working: 代码 - 不工作:
var tree = [{
"name": "Parent 1",
"subcat": []
},
{
"name": "Parent 2",
"subcat": [{
"name": "child 2",
"subcat": [{
"name": "grandchild 2",
"subcat": []
}]
}]
},
{
"name": "Parent 3",
"subcat": []
}
];
buildTree($('#treeList'), tree);
function buildTree($list, nodes) {
$.each(nodes, function(node) {
var $item = $('<li><a href="#">' + node.name + '</a></li>');
if (node.subcat.length) {
var $subList = $('<ul></ul>');
$item.append($subList);
buildTree($subList, node.subcat);
}
$list.append($item);
});
}
Fiddle for not working: https://jsfiddle.net/number40/qmLr14k8/ 不工作的小提琴: https : //jsfiddle.net/number40/qmLr14k8/
I found the error in you code, the each functions first parameter is the index. 我在你的代码中发现了错误,每个函数的第一个参数是索引。
function buildTree($list, nodes) {
$.each(nodes, function(index, node) {
var $item = $('<li><a href="#">' + node.name + '</a></li>');
if (node.subcat.length) {
var $subList = $('<ul></ul>');
$item.append($subList);
buildTree($subList, node.subcat);
}
$list.append($item);
});
Replacing it by this should work. 用它取代它应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.