一只程序媛

执着着我的执着,坚持着我的坚持!不积跬步无以至千里!

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

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>

阅读更多
版权声明:谁没个菜的时候! https://blog.csdn.net/qq_32584661/article/details/80690275
个人分类: Javascript 前端笔记
想对作者说点什么? 我来说一句

50个js经典案例

2015年12月19日 5.7MB 下载

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

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭