js中数组以及for循环的使用

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
div{
    200px;
    height:200px;
    float:left;
    border:1px solid #000;
    margin:20px;
    
    }
</style>
<script>
 window.onload=function()
    {
        var adiv=document.getElementsByTagName("div");
        /*alert (adiv.length);*/
        odiv[2].style.background="red";

    }

</script>
</head>

<body>
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</body>
</html>

给4个div中的任何一个添加背景颜色

<script>
 window.onload=function()
    {
        var adiv=document.getElementsByTagName("div");
        /*alert (adiv.length);*/
        for(i=0;i<4;i++)
        {
            adiv[i].style.background="red" ;
            }

    }

</script>

利用for循环给4个div全部添加背景颜色。

原文地址:https://www.cnblogs.com/kangshuai/p/4668963.html