代码运行效果:

笔者接触JS时间不长,对于传参和封装函数理解不够透彻,经过多次练习稍有感悟,为了加深理解写了这篇简单的隔行换色,希望能对刚接触JS的朋友
有所帮助,以下是程序代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{margin:0;padding: 0;list-style: none}
li{
width: 100%;
height: 40px;
}
div{
width: 100%;
height: 40px;
float: left;
}
</style>
<script>
function turn(tagname,bgcolor1,bgcolor2){//定义参数:1.标签名 2.第一种背景色 3.第二种背景色
var aLi=document.getElementsByTagName(tagname);//使用这个参数
for(var i=0;i<aLi.length;i++){
if(i%2==0){//判断每行的奇偶
aLi[i].style.background=bgcolor1;
}else{
aLi[i].style.background=bgcolor2;
}
}
}
window.onload = function(){
turn('div','red','blue');//调用函数,传递第一种标签名;
turn('li','yellow','green');//传递第二种标签名;
}
</script>
</head>
<body>
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></body></html>下面是运行效果图: