var nodeList = document.all; for(var i in nodeList){ console.log(i+"="+nodeList[i]); } for(var i = 0; i < nodeList.length; i++){ console.log(i+"="+nodeList[i]); }你确定,你的代码中,可以执行到想要的? 而不是像这样?for in的话,会把这个类数组以对象的形式输出,所以会包含一些方法,比如这里我写的代码的输出方式中,for in输出就会有length属性的输出。for循环输出会只会输出其中的数组部分,向length属性,就不会被输出。
for(var i in nodeList){
console.log(i+"="+nodeList[i]);
}
for(var i = 0; i < nodeList.length; i++){
console.log(i+"="+nodeList[i]);
}你确定,你的代码中,可以执行到想要的?
而不是像这样?for in的话,会把这个类数组以对象的形式输出,所以会包含一些方法,比如这里我写的代码的输出方式中,for in输出就会有length属性的输出。for循环输出会只会输出其中的数组部分,向length属性,就不会被输出。
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function change()
{
var val1 = document.getElementById("val1").value;
var val2 = document.getElementById("val2").value;
document.getElementById("display1").innerHTML = parseInt(val1)+ parseInt(val2);
document.getElementById("display2").innerHTML = (parseInt(val1)+ parseInt(val2))*3;
}
</script>
</head>
<body>
<input type="text" id="val1" onchange="change();"/><br/>
<input type="text" id="val2" onchange="change();"/><br/>
总共定了
<div id="display1"></div>件<br/>
总共花费<div id="display2"></div>元<br/>
</body>
</html>
遍历dom对象会把方法什么也遍历出来 。你自己百度看看和传统方法的区别。for in 只能遍历普通的数组和 json。
<form></form>
<form></form>
<img/>
<img/>
<img/>
<a href="#"></a>
<a href=""></a>
</body>
<script type="text/javascript">
var s = '';
var nodeList = document.all;
for(var i in nodeList){
s += i + ':' + nodeList[i];
if(typeof(nodeList[i]) == 'object') s += '[' + nodeList[i].nodeName + ']';
s += '<br>';
}
document.write(s);
</script>length:13
0:[object][HTML]
1:[object][HEAD]
2:[object][TITLE]
ms__id31:[object][FORM]
ms__id32:[object][FORM]
ms__id33:[object][FORM]
6:[object][BODY]
7:[object][IMG]
8:[object][IMG]
9:[object][IMG]
10:http://localhost/ide_tmp.php#[A]
11:http://localhost/[A]
12:[object][SCRIPT]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>for in 遍历dom对象输出对象里面属性</title>
</head>
<body>
<h1>for in 遍历dom对象输出对象里面属性</h1>
<div id="div">
</div>
<script type="text/javascript" language="javascript">
for(pro in document.getElementById("div")){
document.write(pro+'<br />');
}
</script>
</body>
</html>
这个例子就是输出dom对象下的属性
//document.write(nodeList);
console.log(nodelist[i];
}