javascript - 加了闭包,为什么点击时输出的i值还是这样?

查看:125
本文介绍了javascript - 加了闭包,为什么点击时输出的i值还是这样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

var render={
        addEvent: function (elm, evType, fn) {
            if (elm.addEventListener) {
                    elm.addEventListener(evType, fn,false);//DOM2.0
                    return;
                }
            else if (elm.attachEvent) {
                    var r = elm.attachEvent('on' + evType, fn);//IE5+
                    return;
            }
        },

        init:function () {
            var _this=this;
            var selectBtn= document.getElementById('selectItem').getElementsByTagName('div');
            for(var i=0,j=selectBtn.length;i<j;i++){
                (function(){
                    console.log(i);//输出0,1
                    _this.addEvent(selectBtn[i],'click',function () {
                        console.log(this);//点击第一个输出第一个,点击第二个输出第二个
                        console.log(i);//无论点击哪个,输出i值为2。疑问在此
                        if(i===0){
                            this.className="sl active";
                            selectBtn[1].className="jl";

                        }else{
                            this.className="jl active";
                            selectBtn[0].className="sl";
                        }
                    })
                })();
            }
        }
    }
    render.init();

解决方案

for(var i = 0; i < 5; i++) {
    (function(i) {
        setTimeout(function() {
            console.log(i);  
        }, 1000);
    })(i);
}
// 1,2,3,4,5    
for(var i = 0; i < 10; i++) {
    (function() {
        setTimeout(function() {
            console.log(i);  
        }, 1000);
    })();
}
// 5,5,5,5,5

这篇关于javascript - 加了闭包,为什么点击时输出的i值还是这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆