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);
            }
        };
  • 相关阅读:
    LeetCode 258 Add Digits
    LeetCode 231 Power of Two
    LeetCode 28 Implement strStr()
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 21 Merge Two Sorted Lists
    LeetCode 20 Valid Parentheses
    图形处理函数库 ImageTTFBBox
    php一些函数
    func_get_arg(),func_get_args()和func_num_args()的用法
    人生不是故事,人生是世故,摸爬滚打才不会辜负功名尘土
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/6289544.html
Copyright © 2011-2022 走看看