HTML DOM的树结构 [英] Tree structure for HTML DOM
本文介绍了HTML DOM的树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个由Html dom树填充的树结构。我写了一个递归函数,但在页面加载期间,页面变得无法响应。
这里是我的代码
var root = document .documentElement;
var troot = document .getElementById( list);
traverse(root,troot);
function insertAfter(newNode,referenceNode)
{
referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling);
}
function 遍历(parent,tparent)
{
var sib = document .createElement( li 跨度>);
sib.appendChild( document .createTextNode(parent.nodeName));
tparent.appendChild(sib);
var nextSib,nextRoot;
nextSib = document .createElement( li 跨度>);
nextRoot = document .createElement( ul 跨度>);
nextSib.appendChild(nextRoot);
insertAfter(nextSib,sib);
var childs = parent.children;
for ( var i = 0 ; i< childs.length; i ++)
{
traverse(childs [i],nextRoot);
}
}
我的尝试:
我用jquery尝试了这个并且没有工作。我很困惑javascript支持递归或不...
解决方案
当你遍历它时,你正在修改DOM树。每次调用遍历
时,都会在列表中添加一个新的< li>
元素,这会为您提供另一个元素遍历,这意味着你再次调用遍历
,这会增加另一个新的< li>
元素,...
在完成遍历之前不要修改文档。最简单的选择可能是创建一个detatched< ul>
元素作为父元素,并将其附加到< div>
完成后:
var root = 文档跨度> .documentElement;
var troot = document .createElement( ul);
遍历(root,troot);
document .getElementById( listContainer跨度>)的appendChild(troot);
I want to make a tree structure populated by Html dom tree. I write a recursive function but during page load the page becomes inresponsive.
here is my code
var root=document.documentElement;
var troot=document.getElementById("list");
traverse(root, troot);
function insertAfter(newNode, referenceNode)
{
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function traverse(parent, tparent)
{
var sib=document.createElement("li");
sib.appendChild(document.createTextNode(parent.nodeName));
tparent.appendChild(sib);
var nextSib, nextRoot;
nextSib=document.createElement("li");
nextRoot=document.createElement("ul");
nextSib.appendChild(nextRoot);
insertAfter(nextSib, sib);
var childs=parent.children;
for(var i=0; i<childs.length; i++)
{
traverse(childs[i], nextRoot);
}
}
What I have tried:
I've tried this using jquery and not working. I'm confused javascript supports recursion or not...
解决方案
You're modifying the DOM tree as you're traversing it. Each time you calltraverse
, you add a new<li>
element to the list, which gives you another element to traverse, which means you calltraverse
again, which adds another new<li>
element, ...
Don't modify the document until you've finished traversing it. The simplest option is probably to create a detatched<ul>
element to act as the parent, and append it to a<div>
when you've finished:
var root = document.documentElement; var troot = document.createElement("ul"); traverse(root, troot); document.getElementById("listContainer").appendChild(troot);
这篇关于HTML DOM的树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文