简体   繁体   中英

Hexagon Grid Algorithm Fail

I create a game which has as foreground a hexagon grid. I created an algorithm to display the code, but I receive the following error:

Uncaught TypeError: Cannot read property 'appendChild' of null at hexagonPosition.js:34.

 //hexagonPosition.js var hexGrid = document.getElementById("hex-grid"); for (var rows = 0; rows < 20; rows++) { var hexGroup = document.createElement("div"); hexGroup.id = ("hex-group" + rows); for (var cols = 0; cols < 55; cols++) { var hexTile = document.createElement("div"); hexTile.id = ("hex-tile-x" + cols + "-y" + rows); hexTile.setAttribute("class", "hex-tile" + rows); hexGroup.appendChild(hexTile); } hexGrid.appendChild(hexGroup); }
 //style.css .hex { clip-path: polygon(75% 10%, 100% 50%, 75% 90%, 25% 90%, 0 50%, 25% 10%); width: 75px; height: 75px; } .transparent { visibility: hidden; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="..\\CSS\\style.css" /> </head> <body> <div id="WhatShouldResult"> <div class="hex-grid"> <div class="hex-group1"> <div class="hex-tile1"> </div> <div class="hex-tile2"> </div> <div class="hex-tile3"> </div> </div> <div class="hex-group2"> <div class="hex-tile2"> </div> </div> </div> </div> <div class="hex-grid"></div> <script src="../JS/hexagonPosition.js"></script> </body> </html>

The problem is that in the following line you are getting the element by ID.

var hexGrid = document.getElementById("hex-grid");

But in your HTML hex-grid is a class, not an ID.

<div class="hex-grid">

If you change that line of JavaScript to be the following it should work.

var hexGrid = document.getElementsByClassName("hex-grid")[0];

That will get the first element with the class name of hex-grid .

Or of course you could just change the HTML to be an ID instead of a class.

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