javascript - 创建一个 10x10 的单元格区域

标签 javascript jquery html css

我想创建一个单元格字段。该字段的大小为 10x10。当达到一行中的最大单元格数时,它应该开始新的一行。

目前我所有的单元格 div 都放在下面。

function initGame() {

    var mapSize = 10; // create a field of 10x10
    var cellsPerRow = 10; // 10 cells per row

    for (var x = 0; x < mapSize; x++) {
        for (var y = 0; y < mapSize; y++) {
            createCell(x, y); // create a cell on index x (horizontal) and y (vertical)
        }
    }
}

function createCell(x, y) {

    // store this cell position to a data class

    var cellDiv = $("<div></div>"); // create the cell div
    cellDiv.addClass("cell"); // add some css
    $(document.body).append(cellDiv); // add the cell div to the parent
}
.cell{
    height: 50px;
    width: 50px;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">

</body>

最佳答案

为每 10 个单元格创建包装器。

function initGame() {

    var mapSize = 10; // create a field of 10x10
    var cellsPerRow = 10; // 10 cells per row

    for (var x = 0; x < mapSize; x++) {

        $(document.body).append("<div>");
       
        for (var y = 0; y < mapSize; y++) {
            createCell(x, y); // create a cell on index x (horizontal) and y (vertical)
        }
        $(document.body).append("</div>");

    }
}

function createCell(x, y) {

    // store this cell position to a data class

    var cellDiv = $("<div></div>"); // create the cell div
    cellDiv.addClass("cell"); // add some css
    $(document.body).append(cellDiv); // add the cell div to the parent
}
.cell{
    height: 50px;
    width: 50px;
    border-style: solid;
    border-width: 1px;
    border-color: black;
    background: red;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="initGame()">

</body>

关于javascript - 创建一个 10x10 的单元格区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45208347/

相关文章:

javascript - 如何在 Angular http请求的错误和成功回调之间共享变量

php - 使用同一数据表中的 ajax 填充下拉列表

javascript - JSON 错误 : SyntaxError: JSON. 解析:JSON 数据第 2 行第 1 列出现意外字符

html - 网站图标不工作

html - 使用 HTML5 缓存 google map iPhone 离线使用错误

javascript - 如何使叠加效果与图像响应

javascript - 试图在 C++ 中从 JS 重新创建这段代码

javascript - JQuery:使隐藏的跨度可见并闪烁

javascript - 想要水平滚动鼠标滚轮滚动 Nuxt js

javascript - jquery select change event when get selected 选项