JS小功能—选项卡

代码如下:

<!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>选项卡</title>
<style>
    #div1 div{
        width:200px;
        height:200px;
        border:1px solid #000;
        background:#666;
        display:none;}
    .active{
        background:#9F0;}   
</style>
<script>
    window.onload=function(){
        var di=document.getElementById('div1');
        var aBtn=di.getElementsByTagName('input');
        var oDiv=di.getElementsByTagName('div');
        for(i=0;i<aBtn.length;i++){
            aBtn[i].index=i;//通过js添加的属性可以用,在html标签里添加属性index会报错
            aBtn[i].onclick=function(){
                for(i=0;i<aBtn.length;i++){
                    aBtn[i].className=" ";//先把所有点击按钮颜色都去掉,再给当前元素加上
                    oDiv[i].style.display='none'
                }
            //aBtn[i].className="active";  //未知错误:Uncaught TypeError: Cannot set property 'className' of undefined
            this.className="active"; //当前点击元素加上颜色 <!--当前发生事件的元素:aBtn[i]-->
            //oDiv[i].style.display='block';//错误:Uncaught TypeError: Cannot read property 'style' of undefined
            oDiv[this.index].style.display='block';
            }
        }
    };
</script>
</head>
<body>
<div id="div1">
<input type="button" value="Spring"/>
<input type="button" value="Summer"/>
<input type="button" value="Autumn"/>
<input type="button" value="Winter"/>
<div>春天</div>
<div>夏天</div>
<div>秋天</div>
<div>冬天</div>
</div>
</body>
</html>

还有一些问题不是很明白,为什么报错?

aBtn[i].className="active";  //未知错误:Uncaught TypeError: Cannot set property 'className' of undefined
oDiv[i].style.display='block';//错误:Uncaught TypeError: Cannot read property 'style' of undefined

猜你喜欢

转载自blog.csdn.net/qq_39396275/article/details/80778994