javascript 语言精粹的学习(一)
1 var walk_the_DOM = function walk(node,func) { 2 func(node); 3 node = node.firstChild;//取得指定节点的第一个子节点 4 while (node) { 5 walk(node, func); 6 node = node.nextSibling;//取得指定节点的下一个兄弟节点 7 } 8 }
在看到递归的时候看到这段代码。这段代码其实是遍历某个DOM节点(node)下的所有子节点,并且在遍历到的时候,都是执行参数中传入的自定义的方法。
这其实是个一个树的先序遍历的算法,先找子节点,再找兄弟节点。
1 <html> 2 <head> 3 <script language="javascript"> 4 function Window_Load(){ 5 6 //自定义属性depth为2的所有html控件对象 7 var elements = getElementsByAttribute("depth","2"); 8 alert(elements[0].outerHTML); 9 //取得所有width为29的html控件对象 10 var elements = getElementsByAttribute("width","29"); 11 } 12 var walk_the_DOM = function walk(node, func) { 13 debugger; 14 func(node); 15 node = node.firstChild; 16 while (node) { 17 walk(node, func); 18 node = node.nextSibling; 19 } 20 }; 21 22 var getElementsByAttribute = function (att, value) { 23 var results = []; 24 25 walk_the_DOM(document.body, function (node) { 26 var actual = node.nodeType === 1 && node.getAttribute(att); 27 if (typeof actual === 'string' && (actual === value || typeof value !== 'string')) { 29 results.push(node) 30 } 31 }); 32 return results; 33 }; 34 </script> 35 </head> 36 <body onload="Window_Load();"> 37 <div id="node1"> 38 <div id="node11" depth="2" width="30"> dd </div> 39 <div id="node12" depth="2" width="29"> dd </div> 40 <div id="node13" depth="2" width="29"> dd </div> 41 </div> 42 </body> 43 </html>
对于元素节点,nodeType=1
对于文本节点,nodeType=3
对于属性节点,nodeType=2
另外提一下:
对于注释元素,nodeType=8
对于文档元素,nodeType=9
var actual = ((node.nodeType === 1) && node.getAttribute(att)); 等同于 var actual; if(node.nodeType !== 1){ actual = node.nodeType === 1; //得到的是个整型数值(Numeric) }else{ actual = node.getAttribute(att));//得到的是个字串(String) }
<html>
<head>
<script language=
"javascript"
>
function Window_Load(){
//自定义属性depth为2的所有html控件对象
var
elements = getElementsByAttribute(
"depth"
,
"2"
);
alert(elements[0].outerHTML);
//取得所有width为29的html控件对象
var
elements = getElementsByAttribute(
"width"
,
"29"
);
}
var
walk_the_DOM = function walk(node, func) {
debugger;
func(node);
node = node.firstChild;
while
(node) {
walk(node, func);
node = node.nextSibling;
}
};
var
getElementsByAttribute = function (att, value) {
var
results = [];
walk_the_DOM(document.body, function (node) {
var
actual = node.nodeType === 1 && node.getAttribute(att);
if
(
typeof
actual ===
'string'
&&
(actual === value ||
typeof
value !==
'string'
)) {
results.push(node)
}
});
return
results;
};
</script>
</head>
<body onload=
"Window_Load();"
>
<div id=
"node1"
>
<div id=
"node11"
depth=
"2"
width=
"30"
> dd </div>
<div id=
"node12"
depth=
"2"
width=
"29"
> dd </div>
<div id=
"node13"
depth=
"2"
width=
"29"
> dd </div>
</div>
</body>
</html>