JS 递归 循环未完成就被RETURN出来的问题.
在使用JS做递归的树结构时,函数中的FOR被自己给return出来了,导致循环没有完成
var json={
"type":"class",
"text": "root",
"children": [
{
"type":"class",
"text": "children1",
"children": [
{
"type":"class",
"text": "children1_1",
"children": [
{
"type":"value",
"text": "children1_1_value1"
},
{
"type":"value",
"text": "children1_1_value2"
}
]
}
]
},
{
"type":"class",
"text": "children2",
"children": [
{
"type":"value",
"text": "children2_value1"
},
{
"type":"value",
"text": "children2_value2"
}
]
}
]
};
var xml="<root><class value='root'>";
xml += toxml(json['children']);
xml += "</class></root>";
function toxml(json){
var xml_str="";
for(i=0;i<json.length;i++){
if(json[i]["type"]=="class"){
xml_str += "<class value='"+json[i]['text']+"'>";
xml_str += toxml(json[i]['children']);
xml_str += "</class>";
}else{
xml_str += "<val>"+json[i]['text']+"</val>";
}
}
return xml_str;
}
alert(xml);
[解决办法]
children2 节点和 1 分开,自己调用 toxml
[解决办法]
直接遍历json不是更简单吗
[解决办法]
xml和Json的相互转换,下面有你想要的答案。
http://bbs.csdn.net/topics/300052586
[解决办法]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script language="javascript" type="text/javascript"
src="js/jquery-1.4.1.js"></script>
<script type="text/javascript">
var json={"type":"class","text":"children_root","target":{"jQuery17208685037363186575":114},"checked":false,"state":"open","children":[{"type":"class","text":"children1","target":{"jQuery17208685037363186575":114},"checked":false,"state":"open","children":[{"type":"class","text":"children1_1","target":{"jQuery17208685037363186575":114},"checked":false,"state":"open","children":[{"type":"value","text":"children1_1_value1"},{"type":"value","text":"children1_1_value2"}]}]},{"type":"class","text":"children2","target":{"jQuery17208685037363186575":114},"checked":false,"state":"open","children":[{"type":"value","text":"children2_value1"},{"type":"value","text":"children2_value2"}]}]};
var s="<root> <"+json.type+" value=""+json.text+"">";
$(json.children).each(function(k,v){
s+="<"+v.type+" value=""+v.text+"">";
$(v.children).each(function(key,val){
if(val.children!=null&&val.children.length>0){
s+=" <"+val.type+" value=""+val.text+"">";
$(val.children).each(function(ks,vs){
s+="<val>"+vs.text+"</val>";
});
s+=" </"+val.type+">";
}else{
s+="<val>"+val.text+"</val>";
}
});
s+=" </"+v.type+">";
});
s+="</"+json.type+"></root>";
alert(s);
</script>
</head>
<body>
</body>
</html>
这个你看看行吗 你帖出来json串,文件文件真的保存不了。
我测试可以的,