Javascript学习:综合案例3--循环里面套点击事件

版权声明:谁没个菜的时候! https://blog.csdn.net/qq_32584661/article/details/80690275

js自学网站推荐:http://www.51zxw.net/study.asp?vip=4857021

方法一:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <input type="button" value="button1" id="button1">
    <input type="button" value="button2" id="button2">
    <input type="button" value="button3" id="button3">
    <input type="button" value="button4" id="button4">


    <script>

        function coloript() {

            var colorarr=["green","red","blue","orange"];
            var divarr=document.getElementsByTagName("input");

            for(var i=0;i<divarr.length;i++){

                (function (x) {
                    divarr[x].onclick=function () {
                        alert(colorarr[x]);
                    }
                })(i);  //匿名函数自执行传参

            };

        };

        coloript();


    </script>

</body>
</html>

方法二:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <input type="button" value="button1" id="button1">
    <input type="button" value="button2" id="button2">
    <input type="button" value="button3" id="button3">
    <input type="button" value="button4" id="button4">


    <script>

        function coloript2() {

            var colorarr=["green","red","blue","orange"];
            var divarr=document.getElementsByTagName("input");

            for(var i=0;i<divarr.length;i++){

                (function () {
                    var c=i;
                    divarr[i].onclick=function () {
                        alert(colorarr[c]);
                    }
                })();

            };

        };

        coloript2();


    </script>

</body>
</html>

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页