說明:代碼取自網絡,注釋為筆者學習時根據自己的理解所添加
又及:原作者采用了匈牙利變量命名法,如變量為對象,則前綴字母 o,表示為 object。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>for循環遍歷設置所有DIV塊元素背景色為紅色</title> <style> #outer{ /*外部DIV容器,內含3個子DIV*/ width:330px; height:100px; margin:10px auto; /*左右置中*/ } #outer div{ float:left; /*左浮動,水平排列*/ width:100px; height:100px; margin:0 5px; background:black; /*默認背景色為黑色*/ } </style> <script> window.onload = function () { var oDiv = document.getElementById("outer").getElementsByTagName("div"); //鏈式調用,獲取outer中的所有div元素 var oBtn = document.getElementsByTagName("button")[0];//獲取按鈕引用 oBtn.onclick = function () { //給按鈕注冊事件處理程序 for (var i = 0; i < oDiv.length; i++) { //循環遍歷,設置div元素的style屬性的background值為red. oDiv[i].style.background = "red"; } } } </script> </head> <body> <center><button>點擊將DIV變成紅色</button></center> <!--center元素已經廢棄--> <div id="outer"> <!--一個div包含3個子div--> <div></div> <div></div> <div></div> </div> </body> </html>