JS里获取到for循环中i的实时值。

在使用for循环的时候经常发现i的值在子函数里永远为最大值,其中涉及到的作用域问题就不再多说了。只在这里简单说一下使用闭包和自执行函数的解决方法;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=" http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
html,body{
    height: 100%;
    padding: 0;
    margin: 0;
}
.button{
    height: 40px;
    width: 150px;
    position:relative;
    top: 50%; 
    left: 50%;
    margin-top: -20px;
    margin-left: -75px;
}
</style>
</head>
    <body>
        <div class="button">
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button>4</button>
            <button>5</button>
        </div>
        <script>
            var abc=document.getElementsByTagName("button")
      /*for (var i = 0; i <abc.length; i++) {
               this.οnclick=function(){
                alert(i)    //函数获取不到i则去父级寻找, 这时i已经循环为5,所以i永远为5
            }
        };  */
     /*     for (var i = 0; i < abc.length; i++) {
            (function(e){
                alert(e)   //自执行函数,把i传入e,可以获取到i的各个数值
            })(i)
        };*/
         for (var i = 0; i < abc.length; i++) {
            (function(e){  //自执行函数实时把i传入e
                abc[e].οnclick=function(){  //  通过传入的e获取到哪个按钮发生了点击事件
                    alert(e) //弹出e(此处e为i实时对应值)
                }
            })(i)    
        };   //采用闭包和自执行函数获取i
        </script>
    </body>
</html>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值