function Condition(tagName,attrName,attrValue) { this.tagName=tagName; this.middleStart="<tag-name name="\""+tagName+"\"">"; this.middleEnd="</tag-name>" this.child=null; this.childResult=""; } Condition.prototype.addChild=function(childCondition) { this.child=childCondition; this.childResult=this.child.showXml(); } Condition.prototype.getChild=function() { if(this.child==null) { return this; } else { return this.getChild();//这里是递归 } } Condition.prototype.showXml=function() { return this.middleStart+this.childResult+this.middleEnd; } function test1() { var con=new Condition("table",null,null); var con1=new Condition("tr",null,null); var con2=new Condition("td",null,null); var child1=con.getChild(); child1.addChild(con1); var child2=con.getChild(); child2.addChild(con2); var child3=con.getChild(); alert(con.showXml()); }
楼主那样实现的话逻辑会有点问题,刚才写了一段代码,可以实现楼主所说的功能,供楼主作一个参考吧:
[code="js"]/**标签元素类.
_atts是由{attName:'name',attValue:'value'}形式的对象组成的数组.*/
function Element(_tagName,_atts){
this.tagName=_tagName;//标签名.
this.atts=_atts||[];//属性.
this.childNodes=[];//子标签.
}
/**添加子节点.
_element:子节点,Element类的对象.*/
Element.prototype.appendChild=function(_element){
this.childNodes.push(_element);
}
/**给元素添加属性.
_attName:属性名,_attValue:属性值.*/
Element.prototype.addAttribute=function(_attName,_attValue){
this.atts.push({attName:_attName,attValue:_attValue});
}
/**将Element对象转换为XML形式的字符串.*/
Element.prototype.parseToXML=function(){
var xml=[];
xml.push("");
for(var i=0;i xml.push(""+this.atts[i].attValue+"");
}
for(var i=0;i xml.push(this.childNodes[i].parseToXML());//递归遍历子节点.
}
xml.push("");
return xml.join("\n");//组成字符串并返回.
}[/code]
调用方法如下:[code="js"]
var body=new Element("BODY");
var table=new Element("TABLE",[{
attName:"border",
attValue:"0"
},{
attName:"width",
attValue:"100%"
}]);
var tr = new Element("TR");
var td = new Element("TD");
td.addAttribute("border","1px");
td.addAttribute("gbColor","red");
tr.appendChild(td);
table.appendChild(tr);
body.appendChild(table);
alert(body.parseToXML());//输出xml字符串[/code]
递归那好像应该用:
[code="java"]
return this.child.getChild();//这里是递归
[/code]
而且你的:
[code="java"]
Condition.prototype.showXml=function()
{
return this.middleStart+this.childResult+this.middleEnd;
}
[/code]
也不对吧
无限递归的根源在这里:[code="js"]
return this.child.getChild();//这里是递归[/code]
...不过按照我的逻辑,在getChild()里面使用递归貌似没有任何意义.
楼主能不能说明一下想用这段代码是想实现什么样的效果?
这个只要你call一个就会死循环了,自己call自己,应该是this.child.getChild()
ggmmaallee .......yes, I think you are right.