用js制作选项卡

选项卡在网页中十分常见,因此学习js时选项卡是一个不能绕过的东西。

下面是一个简单的选项卡。

在这其中,像我这样的新学者就因为异步卡在13行一直无法理解为什么13行需要aBtn[i].ind=i;  而不能在下面aDiv【i】这样直接使用。

首先可以证明一下如果aBtn.onclick=function()函数中插入 alert(i);弹窗出来的结果始终是i=4;因为在for循环中有函数,函数和for循环不能同步进行,在触发事件执行函数时,for循环已经完成了,此时i为最大值4,这个就是异步。所以需要重新定义按钮的索引。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        window.onload = function(){
            var aBtn = document.getElementsByTagName('button');
            var aDiv =document.getElementsByTagName('div');
            for(var i = 0; i < aBtn.length;i++){
                //给每个按钮绑定一个索引属性  第一个按钮ind 为0  第二个按钮 ind 为1. 第二个按钮ind为2
                aBtn[i].ind = i;
                alert(i);
                aBtn[i].onclick = function(){
                    for(var j = 0;j < aBtn.length;j++){
                        //将所有div 先隐藏 
                        aDiv[j].style.display = 'none';
                        //所有按钮背景颜色先去掉
                        aBtn[j].style.background = '';
                    }
                    //在把对应的div显示 和按钮的背景变蓝
                    //this就是你点击哪个按钮 this就是那个按钮 上面为每一按钮都绑定了一个ind属性 this.ind就是你点击哪个按钮就是指哪个按钮的ind属性  上面说了第一个按钮ind 为0  第二个按钮ind为1 。。。。
                    this.style.background = 'blue';
                    aDiv[this.ind].style.display = 'block';
                }
            }
        }
    </script>
    <style>
        div{
            width: 150px;
            height: 150px;
            border: 1px solid black;
            display: none;
        }
    </style>
</head>
<body>
    <button style="background:blue;">按钮1</button>
    <button>按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>
    <div style="display:block;">1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</body>
</html>

 

posted on 2017-09-25 21:29  小菜园的菜  阅读(219)  评论(0编辑  收藏  举报