javascript 典型闭包的用法

时间:2022-04-15 04:08:19

<body>
<input type="radio" id="radio1" name="readionGroup" />
<input type="radio" id="radio2" name="readionGroup" />
<input type="radio" id="radio3" name="readionGroup" />
<script type="text/javascript" language="javascript">
        var add_the_handlers = function (nodes) {
            var i;
            for (i = 0; i < nodes.length; i += 1) {
                nodes[i].onclick = function (e) {
                    alert(e);
                }
            }
        };
        add_the_handlers(readionGroup);
    </script>
</body>

给每个radio赋一个onclick,上面写发是错误的,都弹出的时候nodes.length 
红色标识的部分是一个上下文,所以当用户点击的时候,一直用到的变量是i=3

------------------------------------------------------------------------------------------

var add_the_handlers = function (nodes) {
            var i;
            for (i = 0; i < nodes.length; i += 1) {
                (function(j){
                    nodes[j].onclick = function () {
                        alert(j);
                    }
                })(i);
            }
        };
        add_the_handlers(readionGroup);

//红色表示的部分是一个上下文