javascript 使用 JQuery for 循环创建 <div> 网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25518243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating <div> grid with JQuery for loop
提问by user3765383
I'm new to web development but have a pretty solid programming background. I've tried multiple ways to create a element programatically based on user input. I'm trying to essentially create a grid through JQuery.
我是 Web 开发的新手,但具有非常扎实的编程背景。我尝试了多种方法来根据用户输入以编程方式创建元素。我正在尝试通过 JQuery 创建一个网格。
I'm tackling this problem by storing the user input into a variable and going through a for loop to create the grid. Here is the code for the .js file:
我正在通过将用户输入存储到一个变量中并通过 for 循环来创建网格来解决这个问题。这是 .js 文件的代码:
var rows = 8;
var columns = 8;
var $row = $("<div />", {class: 'row'});
var $square = $("<div />", {class: 'square'});
$(document).ready(function(){
for(var i = 0; i < rows; i++){
$("#wrapper").append($row);
}
for(var i = 0; i < columns; i++){
$(".row").append($square);
}
});
Now for some reason, this code only creates one row in #wrapper and one square in the row. I've tried copying the example CSS files that tackle this problem but nothing seems to work. Here's what I have right now for my CSS:
现在出于某种原因,此代码仅在 #wrapper 中创建一行,并在该行中创建一个正方形。我尝试复制解决此问题的示例 CSS 文件,但似乎没有任何效果。这是我现在的 CSS:
#wrapper {
width: 850px;
height: 850px;
margin-top: 100px;
margin-left: auto;
margin-right: auto;
background: #000000;
}
.row {
width: auto;
height: 100px;
background: #313131;
}
.square {
width: 100px;
height: 100px;
margin: 0px;
outline: 1px solid;
display: inline-block;
float: left;
background: #FFFFFF;
}
And here's my HTML:
这是我的 HTML:
<!doctype html>
<html>
<head>
<title>Draw Grid</title>
<link rel="stylesheet" type="text/css" href="theme.css" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="draw.js"></script>
</head>
<body>
<div id="wrapper">
</div>
</body>
</html>
Can anybody help me out? I'm so confused. I've tried everything. Is this a CSS formatting error?
有人可以帮我吗?我很混乱。我什么都试过了。这是 CSS 格式错误吗?
回答by Arun P Johny
The problem is you are creating only one row and square objects, you need to use cloned copies else they are just copy
问题是您只创建一行和方形对象,您需要使用克隆副本,否则它们只是复制
var rows = 8;
var columns = 8;
var $row = $("<div />", {
class: 'row'
});
var $square = $("<div />", {
class: 'square'
});
$(document).ready(function () {
//add columns to the the temp row object
for (var i = 0; i < columns; i++) {
$row.append($square.clone());
}
//clone the temp row object with the columns to the wrapper
for (var i = 0; i < rows; i++) {
$("#wrapper").append($row.clone());
}
});
Demo: Fiddle
演示:小提琴