i want to programm a tile map with just 1 picture. It shall be a 5x5 field of small pictures. I have wrote some Javascript Code with 2 nested Loops. With this solution, only 1 pictures is printed. When i remove the br Tag in the second loop, 5 pictures are printed, but only in a row, not among themselves. Whats the problem? How can i realize that?
window.onload=function() {
document.getElementById('button_generateField').addEventListener('click', function generateField (spacefields) {
for (var i = 0; i <= 4; i++) {
var horizontal_field = new Image();
horizontal_field.src = 'Grafiken/spacefields.jpg';
document.body.appendChild(horizontal_field);
for (var j = 0; j <= 4; j++){
var vertical_field = new Image();
vertical_field.src = '/Grafiken/spacefieldsd.jpg';
document.body.appendChild( '<br>' + vertical_field);
};
};
});}
HTML
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Test</title>
<style type="text/css">
</head>
<body>
<div id="header">
<img src="testbanner1.jpg" alt="banner" width="1500" height="150px" >
</div>
<div id="main">
<button id="button_generateField">Generate Field!</button>
</div>
</body>
</html>
/Grafiken/spacefieldsd.jpg
looks like a typo. use document.createElement("img")
instead of new Image()
. your <br>
will not work, you need to document.createElement("br")
var btn = document.getElementById("button_generateField"); var div = document.getElementById("main"); var rows = 4; var cols = 4; var x = 0; var y = 0; btn.addEventListener("click", function(){ for(y=0;y<rows;y++){ for(x=0;x<cols;x++){ var img = document.createElement("img"); img.src = "https://via.placeholder.com/100x100"; img.onload = function(){ } div.appendChild(img); } div.appendChild(document.createElement("br")); } });
<button id="button_generateField">Generate Field!</button> <div id="main"> </div>
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.