JS构建页面的DOM节点结构的实现代码_javascript技巧

WBOY
Release: 2016-05-16 17:58:24
Original
1101 people have browsed it

小提示:
关于数组的concat和push方法。
两者的区别主要有:
concat是连接数组,不会修改原数组,返回值为连接后的数组,与push的重要区别是concat会展开数组的第一层子数组
push是添加数组元素。就地修改原数组,返回值为添加的新项,push不会展开传入的数组。

复制代码代码如下:

var a = [1,2,3,4];
var b = [4,5,6,7];
var c = a.push(b);
var d = a.concat(b);

console.log('a',a);
console.log('b',b);
console.log('c',c);
console.log('d',d);

//输出:
a [1,2,3,4,[4,5,6,7]]//没有展开
b [4,5,6,7]
c 5//push返回新添加的项
d [1,2,3,4,[4,5,6,7],4,5,6,7]//push未展开,concat展开

首先遍历DOM树,然后构建,结果保存形为
复制代码代码如下:

{
key_1:[{key_1_1:value_1},{key_1_1:value_1},{key_2_1:value_2}],
key_2:[],
key_3:[],
key_4:[],
}

的结构

本来想用json格式的,可是要么有重复,要么得嵌套,所以改用对象嵌套数组。
获取了结构之后,节点树基本也就确定了,直接构造成树形菜单就可以了。
当然,还是构成简单的树形菜单,见 http://www.jb51.net/article/29100.htm
遍历和构建的函数如下:
复制代码代码如下:

//遍历节点
function walkDom(el){
var c = el.firstChild;
var retObj = {};
var array = [];
while(c !== null){//这里只是返回了元素节点,没有节点就是个空数组
if(c.nodeType == 1){
array.push(walkDom(c));
}
c = c.nextSibling;
}
retObj[el.tagName] = array;
return retObj;
} //构建树形 function createTree(tree){
var array = [];
for(var key in tree){
array.push('
  • ');
    array.push(key.toLowerCase());
    array.push('

    ');
    if(tree[key].length != 0){
    array.push('
      ');
      for(var i = 0; i array = array.concat(createTree(tree[key][i]));
      }
      array.push('
    ');
    }
    array.push('
  • ');
    }
    return array;
    }

    下面是一个demo:
    复制代码代码如下:

    BR>"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">









    第一部分


















    结果如下(未美化):

    Related labels:
    dom
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!