unction getByClass(clsName, parent){
//定义函数getByClass()实现获取document或指定父元素下所有class为on的元素
var elements=parent?document.getElementById(parent).getElementsByTagName("*"):document.getElementsByTagName("*");;
var arr=[];
for(var i=0;i<elements.length;i++){
if(elements[i].className==clsName){
arr.push(elements[i]);
}
}
return arr;
}
<!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(len2.length); // 结果等于3为正确 } function getByClass(clsName, parent){ //定义函数getByClass()实现获取document或指定父元素下所有class为on的元素 var oparent = parent?document.getElementById(parent):document; var elements = oparent.getElementsByTagName('*'); var result = []; for(var i=0;i<elements.length;i++){ if(elements[i].className == clsName){ result.push(elements[i]); } } return result; } </script>
<!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(len2.length); // 结果等于3为正确
}
function getByClass(clsName, parent){
//定义函数getByClass()实现获取document或指定父元素下所有class为on的元素
var child;
if(parent!=null){
child=document.getElementById(parent).getElementsByTagName("*");
}else{
child=document.getElementsByTagName("*");
}
var onarry=[];
for(var i=0;i<child.length;i++){
if(child[i].className==clsName){
onarry.push(child[i]);
}
}
return onarry;
}
</script>
其实 不是你的错,是本身代码当中就有陷阱,有时候要相信自己,看看老师的代码你就会发现
改(parent==undefined||panrent==null)?xx : xx
函数写错了 function