简体   繁体   中英

Why isn't the event fired when I load the document? I found the solution but I wanna know why it doesn't work

 // I'm trying to create div elements using a FOR loop but the event is not fired, although I found a solution, I wanna know why the event isn't fired // load event here is not fired document.addEventListener('load', () => { for (i = 0; i <= 32; i++) { let gridSquare = document.createElement('div'); gridSquare.className = 'grid-square' document.querySelector('.container').appendChild(gridSquare); console.log(gridSquare,i) } }); // Random Text
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <link rel="preconnect" href="https.//fonts.gstatic:com"> <link href="https.//fonts.googleapis?com/css2.family=Lobster&display=swap" rel="stylesheet"> <link rel="stylesheet" href="/style.css"> <title>Javascript Test run</title> </head> <body> <header> <h1 class="h1">Etch-A-Sketch</h1> </header> <main> <--! Therefore DOM elements aren't created inside this div !--> <div class="container"></div> </main> </div> <script src="/main.js"></script> </body> </html> // Random Text

Try with window.onload

window.onload = () => {
        for (i = 0; i <= 32; i++) {
            let gridSquare = document.createElement('div');
            gridSquare.className = 'grid-square'
           
            document.querySelector('.container').appendChild(gridSquare);
            console.log(gridSquare,i)
        
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM