实际效果

clipboard.png

<!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>
    <style>
        ul,
        li {
            list-style: none;
        }

        .tabBox {
            width: 400px;
            height: 400px;
            border: 1px solid #ccc;
        }

        .tabBox ul {
            display: flex;
            border-bottom: 1px solid #000;
        }

        .tabBox ul li {
            flex: 1;
        }

        .tabBox ul li.select {
            background-color: red;
        }

        .tabBox div {
            display: none;
        }

        .tabBox div.select {
            display: block;
        }
    </style>
</head>

<body>
    <div class="tabBox" id="tabBox">
        <ul>
            <li class="select">新闻</li>
            <li>视频</li>
            <li>音乐</li>
        </ul>
        <div class="select">新闻内容</div>
        <div>视频内容</div>
        <div>音乐内容</div>
    </div>
    <script>
        var tabBox = document.getElementById('tabBox'),
            oList = tabBox.getElementsByTagName('li'),
            oDivList = tabBox.getElementsByTagName('div');

        function changeTab(index) {
            for (var i = 0; i < oList.length; i++) {
                oList[i].className = oDivList[i].className = null;
            }
            oList[index].className = oDivList[index].className = "select";
        }
    </script>
</body>

</html>

for循环后,直接调用事件

        for(var i=0;i<oList.length;i++){
            console.log(i) //0,1,2,3
            oList[i].onclick = function(){
                console.log(i)   //3
                changeTab(i)
            }
        }

打开页面后,直接运行for循环,打印出0,1,2,然后执行i++,所以oList[i].onclick之前i=3;
clipboard.png
再次点击tab栏

clipboard.png

给oList[i],新增一个key:Index,

        for (var i = 0; i < oList.length; i++) {
            oList[i].Index = i;
            oList[i].onclick = function() {
                console.log(i)   //3
                console.log(this.Index )  //0,1,2
                changeTab(this.Index)
            }
        }

点击第一个的时候

clipboard.png

闭包1

利用闭包的保存作用

        for (var i = 0; i < oList.length; i++) {
            oList[i].onclick = (function(i) {
                return function(){
                    console.log(i)  //0,1,2
                    changeTab(i)
                }
            })(i)
        }

闭包1,更优雅

利用闭包的保存作用

        for (var i = 0; i < oList.length; i++) {
            (function(i){
                oList[i].onclick = function(){
                    console.log(i) //0,1,2
                    changeTab(i)
                }
            })(i)
        }

es6

let块级作用域

        for (let i = 0; i < oList.length; i++) {
            oList[i].onclick = function(){
                    console.log(i)  //0,1,2
                    changeTab(i)
                }
        }

渣渣辉
1.3k 声望147 粉丝