以下是整个页面:
<html>
<head>
<script type="text/javascript" src="/jquery.js"></script>
<script type="text/javascript" src="/json2.js"></script>
<script type="text/javascript">
function buildList(point) {
if ( !point )
return [];
children = [];
lis = point.children('li');
for (index = 0; index < lis.length; index++) {
id = $(lis[index]).attr('id');
parts = id.split('-');
title = $(lis[index]).children('div').text();
newObj = {
id: parts[1],
mtype: parts[0],
label: title
}
ol = $(lis[index]).children('ol');
// if (ol.length == 1) {
// newObj['childobjects'] = buildList(ol);
// }
children.push(jQuery.extend(true, {}, newObj));
}
return children;
}
$(function() {
obj = buildList( $('#menu-top') );
alert( JSON.stringify(obj) );
});
</script>
</head>
<body>
<ol id="menu-top" class="sortable ui-sortable">
<li id="entry-16608">
<div>Test item 1</div>
<ol>
<li id="entry-16607" ">
<div>News, links and random thoughts</div>
</li>
</ol>
</li>
<li id="entry-16609">
<div>How a data retention mandate will likely lead to de facto censorship in the US</div>
</li>
<li id="entry-16579">
<div>Git cheat sheet</div>
</li>
</ol>
</body>
</html>
当我注释掉递归调用时,我的JSON看起来像这样:
[
{
"id":"16608",
"mtype":"entry",
"label":"Test item 1"
},
{
"id":"16609",
"mtype":"entry",
"label":"How a data retention mandate will likely lead to de facto censorship in the US"
},
{
"id":"16579",
"mtype":"entry",
"label":"Git cheat sheet"
}
]
当我取消注释代码时,JSON看起来像这样:
[
{
"id":"16607",
"mtype":"entry",
"label":"News, links and random thoughts"
},
{
"id":"16607",
"mtype":"entry",
"label":"News, links and random thoughts"
}
]
我猜这是因为我对JavaScript如何处理作用域和递归的更详细的细节无知,但我不知道该怎么做。
答案 0 :(得分:4)
是的,这是一个范围问题。您忘记将var
放在所有变量前面。这使变量成为全局变量,这意味着每个函数调用都可以访问相同的变量(并覆盖它们)。
查看固定版本:http://jsfiddle.net/fkling/uYXYh/
您可以通过使用更多jQuery方法来进一步改进代码:
function buildList(point) {
if (!point) return [];
var children = [];
point.children('li').each(function() {
var parts = this.id.split('-');
var newObj = {
id: parts[1],
mtype: parts[0],
label: $(this).children('div').text()
};
var $ol = $(this).children('ol');
if ($ol.length == 1) {
newObj['childobjects'] = buildList($ol);
}
children.push(jQuery.extend(true, {}, newObj)); // not sure why you are
// doing this instead of
// children.push(newObj)
});
return children;
}
答案 1 :(得分:1)
似乎index
被声明为全局变量,并且在每次调用buildList时都会发生变异。我认为这是你的问题(但也许你是故意这样做的,我没有看到)。尝试将for语句更改为:
for(var index=0; index < lis.length; index++){
// ...
}