自己实现string的substring方法 人民币小写转大写,(2)


function traversalByNextSibling(obj){
var ch=obj.firstChild,
result=[];
do{
result.push(ch.nodeName);
if(ch.childNodes.length){
result.push.apply(result,traversalByNextSibling(ch));
}
}while(ch=ch.nextSibling);
return result;
}


方法二:用childNodes

复制代码 代码如下:


function traversalByChildNodes(obj){
var ch=obj.childNodes,
result=[];
for(var i=0,j=ch.length;i<j;i++){
result.push(ch[i].nodeName);
if(ch[i].childNodes.length){
result.push.apply(result,traversalByChildNodes(ch[i]));
}
}
return result;
}


测试:

复制代码 代码如下:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style type="text/css">

</style>
</head>
<body>
<div>Test</div>
<div>Hello World</div>
<p>PTest</p>
<script>
console.log(traversalByNextSibling(document));
//IE6-8: #comment,HTML,HEAD,TITLE,META,STYLE,BODY,DIV,#text,DIV,#text,P,#text,SCRIPT
//other:["html", "HTML", "HEAD", "#text", "META", "#text", "TITLE", "#text", "#text", "STYLE", "#text", "#text", "#text", "BODY", "#text", "DIV", "#text", "#text", "DIV", "#text", "#text", "P", "#text", "#text", "SCRIPT", "#text"]

console.log(traversalByChildNodes(document));
//IE6-8: #comment,HTML,HEAD,TITLE,META,STYLE,BODY,DIV,#text,DIV,#text,P,#text,SCRIPT
//otehr:["html", "HTML", "HEAD", "#text", "META", "#text", "TITLE", "#text", "#text", "STYLE", "#text", "#text", "#text", "BODY", "#text", "DIV", "#text", "#text", "DIV", "#text", "#text", "P", "#text", "#text", "SCRIPT", "#text"]
</script>
</body>
</html>


在IE6-8中把换行去掉了,在其他浏览器中把换行作为一个文本节点,所以会有很多#text,但IE6-8中出现了#comment我现在也没明白为什么。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wddspx.html