最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the most efficient way to create a clickable grid with htmljs? - Stack Overflow

programmeradmin2浏览0评论

I'm trying to set up a minesweeper-ish kind of game I can share with my Dad over the web. How would I use a loop to create that grid and make each index at a certain coordinate that I can manipulate? Thanks everyone.

I'm trying to set up a minesweeper-ish kind of game I can share with my Dad over the web. How would I use a loop to create that grid and make each index at a certain coordinate that I can manipulate? Thanks everyone.

Share Improve this question asked Apr 23, 2016 at 1:40 MkzMkz 12 silver badges6 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You can use a multi-dimensional array (an array of arrays).

var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        grid[y].push(0);
    }
}

You now have a 10x10 grid, which you can access via grid[x][y]

Representing this on the page, in HTML, depends on the framework you are using. If you want to do it with raw javascript, you could perhaps output a table.

document.write('<table>');
var gridWidth = 10;
var gridHeight = 10;
var grid = [];
for(var y = 0; y < gridHeight; y++)
{
    document.write('<tr>');
    grid.push([]);
    for(var x = 0; x < gridWidth; x++)
    {
        document.write('<td onclick="alert(\'clicked\');">');
        grid[y].push(0);
        document.write('</td>');
    }
    document.write('</tr>');
}
document.write('</table>');

This will give you some click events, reporting back the column and row.

css:

td {
    border: black solid 1px;
}

html:

<table class="table"></table>

javascript:

$('.table').on('click', 'td', function () {
    console.log($(this).attr('data-row'));
    console.log($(this).attr('data-column'));
})

var columns = 10, rows = 10

function createGrid(columns, rows) {
    var table = $('.table');

    for (var i = 0; i < rows; i++) {
        var row = $('<tr>');
        table.append(row)
        for (var j = 0; j < columns; j++) {
            var cell = $('<td>')
            cell.attr('data-row', i);
            cell.attr('data-column', j)
            row.append(cell);
        }
    }
}
createGrid(columns, rows);
发布评论

评论列表(0)

  1. 暂无评论