码迷,mamicode.com
首页 > 其他好文 > 详细

NodeList对象的学习

时间:2015-04-09 23:20:13      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

书上原话:每个节点都有一个childNodes属性,其中保存这一个NodeList对象。NodeList是一个“类数组的对象”。NodeList是有生命的、有呼吸的对象。而不是我们第一次访问时的某个瞬间的一个快照。

  

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>NodeList的学习</title>
<script type="text/javascript">
	window.onload = function(){
		var oUl = document.getElementsByTagName("ul")[0];		
		//console.log(oUl.childNodes.length);//9而不是4
		console.log(oUl.children.length); //4
		console.dir(oUl.childNodes);
		console.dir(oUl.children);
		//检查children取到的是数组还是NodeList对象
		var test = oUl.children;		
		console.log(test.item(0));//test有item方法初步证明children取到是NodeList对象

		//将NodeList对象转换为数组(在IE8及以前的版本不兼容)
		var arrayNodes = Array.prototype.slice.call(oUl.childNodes,0);
		console.log(arrayNodes);
		var arrayNodes1 = convertToArray(oUl.childNodes);
		console.log(arrayNodes1);	
	};

	//将NodeList对象转换为数组(方法二)
	function convertToArray(nodes){
		var array = null;
		try{
			array = Array.prototype.slice.call(nodes,0);
		}catch(ex){
			array = new Array();
			for(var i = 0,len = nodes.length; i <len; i ++){
				array.push(nodes[i]);
			}
		}

		return array;
	}
</script>
</head>
<body>
<h1>每个节点都有一个childNodes属性,其中保存这一个NodeList对象。NodeList是一个“类数组的对象”</h1>
<h2>NodeList是有生命的、有呼吸的对象。而不是我们第一次访问时的某个瞬间的一个快照</h2>
<ul>
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
</ul>
</body>
</html>

  

知识总结:

  1、NodeList是一个类数组

  2、childBodes属性可能会取到自己不想取到的节点例如textNode节点。children可以很好的解决该问题。

  3、如何判断一个对象是类数组还是真的数组观察console的结果数组[]都带着这个表示

  4、其余的知识点都在代码的注释中注意复习

NodeList对象的学习

标签:

原文地址:http://www.cnblogs.com/MR-K/p/4412093.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!