Javascript 如何获取DOM的提取
我得到了一个*.svg文件,我正在这个函数中迭代遍历它Javascript 如何获取DOM的提取,javascript,xml,dom,Javascript,Xml,Dom,我得到了一个*.svg文件,我正在这个函数中迭代遍历它 function traverseSVG( root ){ var stack = [root]; var c; var item = new Item( "root" ); item.parent = item; while( stack.length > 0 ){ c = stack[ stack.length - 1 ]; if( c.nodeType =
function traverseSVG( root ){
var stack = [root];
var c;
var item = new Item( "root" );
item.parent = item;
while( stack.length > 0 ){
c = stack[ stack.length - 1 ];
if( c.nodeType == 1 && c.childNodes.length > 0 ){
stack.push( c.firstChild );
} else if( c.nextSibling != null ){
stack.pop();
stack.push( c.nextSibling );
} else {
while( stack.length > 0 ){
c = stack.pop();
if( c.nextSibling != null ){
stack.push( c.nextSibling );
break;
}
}
}
}
}
在item变量中,我喜欢存储一些满足特定条件的元素。item变量具有以下构造函数:
function Item( e ) {
this.e = e;
this.children = [];
this.parent = null;
}
Item.prototype.addChild = function( c ){
this.children.push( c );
c.setParent( this );
return c;
}
Item.prototype.setParent = function( p ){
this.parent = p;
return p;
}
例如,如果输入svg如下所示,则该项应存储所有组和路径元素,并注意层次顺序。因此,在新树中不应包括defs元素,但defs元素内的组应成为defs父级的直接子级。这类似于输入DOM的提取
考虑一下,如果新DOM中应该包含输入元素,那么还有一个测试函数返回true或false。我的问题是:如何将其包括在遍历函数中,best?问题是当遍历在DOM中深入并再次出现时,要跟踪正确的当前项。我试了很多,但没有解决办法
提前谢谢你的帮助
你好,菲利普,经过一段时间的绞尽脑汁,我终于成功了。对于所有可能执行类似任务的人,我的解决方案如下:
function traverseSVG( root ){
var stack = [root];
var c, i;
var item = new Item( root );
item.parent = item;
while( stack.length > 0 ){
i = null;
c = stack[ stack.length - 1 ];
if( Item.isItem( c ) && item.canAppend ){
i = new Item( c );
item.addChild( i );
}
if( c.nodeType == 1 && c.childNodes.length > 0 ){
stack.push( c.firstChild );
if( i != null ){
item = i;
}
} else if( c.nextSibling != null ){
stack.pop();
stack.push( c.nextSibling );
} else {
while( stack.length > 0 ){
c = stack.pop();
if( c === item.e ){
item = item.parent;
}
if( c.nextSibling != null ){
stack.push( c.nextSibling );
break;
}
}
}
}
}
在新项目中使用i变量就可以做到这一点。问候