zoukankan      html  css  js  c++  java
  • 点击记数

    普遍的写法:

    <!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="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="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);
            }
        };
  • 相关阅读:
    组件库设计
    kill 3000
    nextjs服务端渲染原理
    Web交互增强
    webpack4.0打包的时候一些技巧
    把网站部署到阿里云上的步骤
    typescript使用小结
    webpack 4.0尝鲜
    基于Quick-cocos2d-x的资源更新方案 二
    Android APK是否需要预解压
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/6289544.html
Copyright © 2011-2022 走看看