首页 > 关于循环结束后获取不到点击事件想要的对象

关于循环结束后获取不到点击事件想要的对象

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            body,html {margin: 0;padding: 0;}
            nav {width: 100px;height: 25px;border: 1px solid rosybrown;color: #fff;float: left;text-align: center;line-height: 25px;}
        </style>
    <script type="text/javascript">
    window.onload = function() {
        var arr = [{
            title: "科技",
            bgcolor: "blue",
            currentbg: "block",
            hash: "keji"
        }, {
            title: "军事",
            bgcolor: "blue",
            currentbg: "yellow",
            hash: "junshi"
        }, {
            title: "新闻",
            bgcolor: "blue",
            currentbg: "red",
            hash: "xinwen"
        }];
        var adom = [];
        for (var attr in arr) {
            if (!arr.hasOwnProperty(attr) || ("title" in arr[attr] && arr[attr]["title"] !== "")) {
                var oNav = document.createElement("nav");
                oNav.innerHTML = arr[attr]["title"];
                oNav.style.backgroundColor = arr[attr]["bgcolor"];
                oNav.setAttribute("data-hash", arr[attr]["hash"]);
                document.querySelector("body").appendChild(oNav);
                adom.push(oNav);
                oNav.onclick = function() {
                    var hash = this.dataset.hash; //获取hash
                    window.location.hash = hash; //传给url
                    for (var j in adom) {
                        adom[j].style.backgroundColor = arr[j]["bgcolor"];
                    }
                    //我这里想获取当前选中状态下他对应的背景颜色在arr下的currentbg下
                    //比如我当前选中状态是第2个nav对应的就是this.style.backgroundColor="yellow"
                    this.style.backgroundColor = ;
                };
                window.onhashchange = function() { //url发现改变页面跟着变
                    hashchange();
                }
                hashchange();

                function hashchange() {
                    var firstHash = window.location.hash.substring(1) || "";
                    for (var key in arr) {
                        document.querySelector("." + arr[key]["hash"]).style.display = "none";
                    }
                    if (firstHash) {
                        document.querySelector("." + firstHash).style.display = "block";
                    }
                };
            }
        }
    }
</script>
    </head>
    <body>
        <div data-hash="keji" class="keji">科技版块</div>
        <div data-hash="junshi" class="junshi" style="display: none;">军事版块</div>
        <div data-hash="xinwen" class="xinwen" style="display: none;">新闻版块</div>
    </body>
</html>

使用闭包缓存临时变量吧


oNav.onclick = function(oldAttr){
                return function() {
                    var hash = this.dataset.hash; //获取hash
                    window.location.hash = hash; //传给url
                    for (var j in adom) {
                        adom[j].style.backgroundColor = arr[j]["bgcolor"];
                    }
                    //我这里想获取当前选中状态下他对应的背景颜色在arr下的currentbg下
                    //比如我当前选中状态是第2个nav对应的就是this.style.backgroundColor="yellow"
                    this.style.backgroundColor = oldAttr.currentbg;
                };
            }(arr[attr]);
            

如果我没理解错,你想在事件处理器里面访问循环中的变量arr,但是当你的循环执行完了,你的事件处理器真正触发是在循环执行完之后,attr已经变成了最后一个。
看下我评论里面给你提供的那个链接吧。。。


<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style>
            body,html {margin: 0;padding: 0;}
            nav {width: 100px;height: 25px;border: 1px solid rosybrown;color: #fff;float: left;text-align: center;line-height: 25px;}
        </style>
    <script type="text/javascript">
    window.onload = function() {
        var arr = [{
            title: "科技",
            bgcolor: "blue",
            currentbg: "black",
            hash: "keji"
        }, {
            title: "军事",
            bgcolor: "blue",
            currentbg: "yellow",
            hash: "junshi"
        }, {
            title: "新闻",
            bgcolor: "blue",
            currentbg: "red",
            hash: "xinwen"
        }];

        var adom = [],
            item,
            OnClick = function() {//导航的 onclick 事件
                var hash = this.getAttribute('data-hash'); //获取hash
                location.hash = hash; //传给url
                //还原其他导航的背景颜色
                for (var j = adom.length; j--;) {
                    adom[j].style.backgroundColor = arr[j].bgcolor;
                }
                //设置当前的
                this.style.backgroundColor = arr[this.getAttribute('data-index') * 1].currentbg;
            };

        for (var i = arr.length; i--;) {
            item = arr[i];
            if (item.title) {
                var oNav = document.createElement("nav");
                oNav.innerHTML = item.title;
                oNav.style.backgroundColor = item.bgcolor;
                oNav.setAttribute("data-hash", item.hash);
                oNav.setAttribute("data-index", i);
                adom.push(oNav);
                oNav.onclick = OnClick;
                document.body.appendChild(oNav);
            }
        }
    }

    function hashchange() {
        var firstHash = window.location.hash.substring(1) || "";

        for (var i = arr.length; i--;) {
            document.querySelector("." + arr[i]["hash"]).style.display = "none";
        }
        if (firstHash) {
            document.querySelector("." + firstHash).style.display = "block";
        }
    };

    window.onhashchange = hashchange; //url发现改变页面跟着变
</script>
    </head>
    <body>
        <div data-hash="keji" class="keji">科技版块</div>
        <div data-hash="junshi" class="junshi" style="display: none;">军事版块</div>
        <div data-hash="xinwen" class="xinwen" style="display: none;">新闻版块</div>
    </body>
</html>
  1. 正常的数组请使用 for 去遍历, 而不是 for in.

  2. 不要在循环体内重复生成 函数.

  3. 在创建的时候,将其所对应的 索引值 i 赋值给这个元素的某个属性(此处为data-index),

    然后就可以在需要的时候, 读取这个属性, 得到它在`arr`数据中的位置, 就可以取数据了.
  4. 在使用 arr[attr] 的时候, 可以将其赋值给一个变量, 这个不用每次都写 arr[attr], 而是直接写变量名就可以了.

【热门文章】
【热门文章】