下面是整个页面:
<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如何处理作用域和递归的细节一无所知,但我不知道该怎么做。
发布于 2011-02-21 02:27:18
是的,这是一个范围问题。您忘记了将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;
}发布于 2011-02-21 02:23:08
似乎index被声明为全局变量,并且在每次调用buildList时都会发生变化。我认为这就是你的问题(但也许你是故意这么做的,而我没有注意到)。尝试将for语句更改为:
for(var index=0; index < lis.length; index++){
// ...
}https://stackoverflow.com/questions/5058889
复制相似问题