In the code below, I take the number of square the user wants, then calculate the size of each square (so that they all fit in the container.)
I then define var square
as in the 3rd line of code. I find this string pasting technique very hard to read and error-prone. The general question is thus: Is there a better way to define an element using user input?
var genGrid = function(num_square) {
var square_size = ($(".grid_container").height() / num_grid) + "px";
var square = "<div class='square' style='height:" + square_size + ";\
width: " + square_size + "'></div>";
$("body").append($(square));
};
1 Answer 1
As you have already stated passing an HTML string is not the best way to create a new DOM element. You can create a new one using plain Javascript, like this:
var newDiv = document.createElement('div');
and together with few changes to your code, function could look similar to this:
function generateGrid(numGrid) {
var squareSize = $('.grid_container').height() / numGrid;
var $square = $(document.createElement('div')); // we create and fetch a new element
// here come some handy methods from jQuery, please check'em out on jquery.com
$square.width(squareSize).height(squareSize).addClass('square');
$('.grid_container').append($square);
}
generateGrid(4);
Hope this will help you!
-
\$\begingroup\$ Oh, the reason why I did not define
$square
as an element is because I have to append square multiple times. Can I just dovar square = "(document.createElement('div'))"
then? \$\endgroup\$Heisenberg– Heisenberg2014年03月29日 00:47:47 +00:00Commented Mar 29, 2014 at 0:47 -
1\$\begingroup\$ I have created a jsFiddle for you so you can play with the code. As you can see I've splitted this problem into two functions. One of them simply builds a square element and second one is responsible for drawing a grid. Just take a look: link \$\endgroup\$9orky– 9orky2014年03月29日 00:57:00 +00:00Commented Mar 29, 2014 at 0:57
num_square
come in? \$\endgroup\$