创建< div>使用JQuery for循环的网格 [英] Creating <div> grid with JQuery for loop

查看:110
本文介绍了创建< div>使用JQuery for循环的网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是网络开发新手,但具有非常稳定的编程背景。我已经尝试了多种方式基于用户输入以编程方式创建元素。我尝试通过JQuery创建网格。

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.

我通过将用户输入存储到变量并通过for循环创建格。这里是.js文件的代码:

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:

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);
    }
});

现在由于某种原因,这段代码只在#wrapper中创建一行,在行中创建一个正方形。我试图复制解决这个问题的示例CSS文件,但似乎没有任何工作。这是我现在的CSS:

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 {
    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;
}

以下是我的HTML:

And here's my 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>

任何人都可以帮我吗?我很困惑。我已经尝试了一切。这是一个CSS格式化错误?

Can anybody help me out? I'm so confused. I've tried everything. Is this a CSS formatting error?

推荐答案

问题是你只创建一个行和方形对象,你需要使用克隆副本,他们只是复制

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());
    }
});

演示:小提琴

这篇关于创建&lt; div&gt;使用JQuery for循环的网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆