首页 新闻 会员 周边

关于js的问题

0
悬赏园豆:40 [已解决问题] 解决于 2018-04-12 19:40
<!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:nth-child(1) {
            background: #00ffff;
        }
        
        ul li:nth-child(2) {
            background: #0011ff;
        }
        
        ul li:nth-child(3) {
            background: #ff00ff;
        }
        
        ul li:nth-child(4) {
            background: #aaffff;
        }
        
        ul li:nth-child(5) {
            background: #ffff00;
        }
        
        ul li:nth-child(6) {
            background: #00ff00;
        }
    </style>
</head>

<body>
    <input type="button" value="a">
    <input type="button" value="b">
    <input type="button" value="c">
    <input type="button" value="d">
    <input type="button" value="e">
    <input type="button" value="f">

    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
        <li>6</li>
    </ul>
    <script>
        var oInput = document.getElementsByTagName("input");
        var oLi = document.getElementsByTagName("li");
        for (var i = 0; i < oInput.length; i++) {
            oInput[i].index = i;
            oInput[i].onclick = function() {
                for (var j = 0; j < oLi.length; j++) {
                    console.log(i); //i输出为6
                    oLi[j].style.display = "block";

                }
                console.log(i); //i输出为6
                oLi[this.index].style.display = "none";
            }
        }
    </script>
</body>

</html>

为什么这两个输出的i都为6,不应该是点击根据点击不同的input标签i是变化的吗?希望能仔细讲解,谢谢

js
花语剑情的主页 花语剑情 | 初学一级 | 园豆:5
提问于:2018-04-10 22:36
< >
分享
最佳答案
0

是因为for循环在你保存的时候就应经执行完了,单机事件里面的i是输出的最后一个i,也就是6

收获园豆:15
Zero77 | 菜鸟二级 |园豆:211 | 2018-04-11 08:20
其他回答(2)
0

for循环都是执行完了之后显示的,你这个应该是6个按钮对应6个li 点一个对应的li显示  js写不方便,用jquery一行就行了。

收获园豆:5
河畔 | 园豆:738 (小虾三级) | 2018-04-11 10:35
0

闭包问题,所有的input的onclick函数持有的都是同一个i。执行onclick方法的时候,i已经变成了6.

收获园豆:5
授之以渔 | 园豆:1107 (小虾三级) | 2018-04-12 10:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册