点击记数

普遍的写法:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="22">
<input type="button" value="22">
<input type="button" value="22">
<input type="button" value="22">
<div id="a" style="width:100px;height:100px;background:green;"></div>
</body>
</html>
<script type="text/javascript">
    window.onload = function () {
        var obtn = document.getElementsByTagName("input");
        var i=0;
        for(i=0;i<obtn.length;i++){
            aa(obtn[i]);
        }
    };
    function aa(obj)
    {
        var count = 0;
        obj.onclick = function () {
            console.log(count++);
        };
    }
</script>
复制代码

 

另一种写法:

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="button" value="22">
<input type="button" value="22">
<input type="button" value="22">
<input type="button" value="22">
<div id="a" style="width:100px;height:100px;background:green;"></div>
</body>
</html>
<script type="text/javascript">
    window.onload = function () {
        var obtn = document.getElementsByTagName("input");
        var i=0;
        for(i=0;i<obtn.length;i++){
            (function (obj){
                var count = 0;
                obj.onclick = function () {
                    console.log(count++);
                };
            })(obtn[i]);
        }
    };
</script>
复制代码

 

注意aa(obtn[i])的写法转变为(fn)(obtn[i]),可以不用写函数名,把传入的参数放到方法的后面

繁琐的写法:

复制代码
    window.onload = function () {
        var obtn = document.getElementsByTagName("input");
        var i=0;
        for(i=0;i<obtn.length;i++){
                obtn[i].onclick = function (count) {//省去变量的声明
                    return function () {
                        console.log(count++);
                    }
                }(0);
        }
    };
复制代码

 

posted @   最爱小虾  阅读(205)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示