<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<p>class为on的p标签</p>
</body>
</html>
<script type="text/javascript">
window.onload=function(){
var len1= getByClass('on','list');
alert(len1.length); // 结果等于2为正确
var len2= getByClass('on');
alert(len1.length); // 结果等于3为正确
}
function getByClass(clsName, parent){
//定义函数getByClass()实现获取document或指定父元素下所有class为on的元素
var oparent=parent?document.getElementById(parent):document;
Arr=new Array();
var oElements=oparent.getElementsByTagName('*');
for(var i=0;i<oElements.length;i++){
if(oElements[i].className==clsName)
Arr.push(oElements[i]);
}
return Arr;
}
</script>
var len1= getByClass('on','list');
alert(len1.length); // 结果等于2为正确
var len2= getByClass('on');
alert(len1.length); // 结果等于3为正确
给的模板错了,将这个代码中第二处的len1.length改为len2.length就好了
是两个0,你到底在问什么?