简体   繁体   中英

Attempting to draw grid elements with Javascript and CSS

I want to create a grid of squares. For this, I made a two dimensional array that will produce a div in a certain position (which is supposed to be it's position times 4px, since that is the size of each square) I don't know what I'm doing wrong since my browser shows no errors. I know something is wrong because nothing is printed when I activate this function. Just to be clear, I already assigned CSS properties to elements of the 'alive' and ' dead' class, and added the 'canvas' id at the end of the page, so I assume the error lies within the creation of the divs themselves. Is creating divs over and over even the correct practice when making a grid? I digress. Thanks for your time.

$(document).ready(function () {
    "use strict";
    $("#btnstart").click(function () {
        for (i = 0; i < xclength; i++) {
            for (j = 0; j < yclength; j++) {
                if (xycoords[i][j] === 1) { //if cell is alive
                    jQuery('<div/>', {
                        className: 'alive',
                        id: "x" + j + "y" + i,
                        css: {
                            position: "absolute",
                            top: (i * 4) + "px",
                            left: (j * 4) + "px"
                        }
                    }).appendTo('#canvas');
                } else { //if cell is dead
                    jQuery('<div/>', {
                        className: 'dead',
                        id: "x" + j + "y" + i,
                        css: {
                            position: "absolute",
                            top: (i * 4) + "px",
                            left: (j * 4) + "px"
                        }
                    }).appendTo('#canvas');
                }
            }
        }
    });
});

Here is a way to make a grid out of div tags. Live example here: http://jsfiddle.net/3x1kmcme/

var rows = 8,
    cells = 8,
    count = 0;

var i, j,
    top = 0,
    left = 0;

var boxWidth = 50,
    boxHeight = 50;

var $canvas = $('#canvas');
var $fragment = $(document.createDocumentFragment());

function addBox(opts) {
  var div = document.createElement('div');
  div.id = opts.id;
  div.className = 'alive';
  div.style.top = opts.top + "px";
  div.style.left = opts.left + "px";

  div.innerHTML = '<p>' + opts.count + '</p>';
  $fragment.append(div);
}

for (j = 0; j < rows; j += 1) {
  top = j * boxHeight;

  for (i = 0; i < cells; i += 1) {
    count += 1;

    addBox({
        count: count,

        id: 'item' + i,
        top: top,
        left: i * boxWidth
    });
  }
}

// Append all
$canvas.html($fragment);

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