[英]Can someone explain me this function for creating grid with JS/jQuery?
I am learning jquery/js and I want to create grid made of divs. 我正在学习jquery / js,我想创建由div组成的网格。 This is script doing just that, but I cant fully understand it..
这只是脚本,但是我无法完全理解它。
function displayGrid (n) {
var size = 960;
var boxSize = (960 - 4*n)/n;
var wrap = $(".wrap").html("");
for (var j = 0; j < n; j++) {
for (var i = 0; i < n; i++) {
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
}
wrap.append($("<div></div>").css("clear", "both"));
}
}
In html I have empty wrap class. 在html中,我有空包装类。
Also, there is this function which I understand :) 另外,我了解这个功能:)
function setGrid() {
var col = prompt("Enter number of columns: ");
displayGrid(col);
clean();
}
Thanks 谢谢
Here is a basic line by line explanation.. 这是逐行的基本说明。
function displayGrid (n) {
var size = 960; //MAX SIZE TO BE COVERED BY ALL DIVS ,EVEN IF THERE ARE N NO OF DIV'S
var boxSize = (960 - 4*n)/n; //FORMULA TO DECIDE WIDTH OF EACH DIV,CAN BE DIFFERENT TOO.
var wrap = $(".wrap").html(""); //THIS IS A DIV PROBABLY WHERE YOU ARE ADDING THE NEW SMALLER DIVS
for (var j = 0; j < n; j++) {
for (var i = 0; i < n; i++) {
//TWO FOR LOOPS ,1 IS FOR LOOP THROUGH ROWS , OTHER FOR COLUMNS.
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
//THIS APPENDS A BLANK DIV TO DIV WITH CLASS .WRAP, AND ADDS A CLASS SQAURE, AND ALSO WITH WIDTH AND HEIGHT PROPERTY SETS EACH DIVS PROPERTY OF WIDTH AND HEIGHT.
}
wrap.append($("<div></div>").css("clear", "both"));
//THIS SHOULD BE TO MOVE TO NEXT COLUMN.
} }
Here is commented code: 这是注释的代码:
//n-> seems to be the number of times to divide the grid
//1-> will get 1 square
//2-> will get 4 square
//3-> will get 9 square and so on... n^2
function displayGrid (n) {
var size = 960;
//This seems to calculate size of the squares to fit inside the give area
// of 960: 960/4
//-4*n I guess is the border size to remove from each square in order to have an exact match
var boxSize = (960 - 4*n)/n;
//this get the grit container, empties it
var wrap = $(".wrap").html("");
//now print each square on the document
for (var j = 0; j < n; j++) { //columns
for (var i = 0; i < n; i++) { //rows
wrap.append( $("<div></div>").addClass("square").height(boxSize).width(boxSize) );
}
//this is done to go in the next row, since we are using divs...
wrap.append($("<div></div>").css("clear", "both"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.