0

我正在尝试使用 jQuery 制作简单的数字游戏。我使用 html 表格构建了一个 7x7 网格。我创建了一些 jQuery 函数来允许用户突出显示和取消突出显示表格中的单元格。我想让用户选择的第一个单元格必须位于最左侧的列中,然后选择的每个后续单元格必须与突出显示的单元格相邻,直到它们将单元格一直连接到右侧桌子。这些单元格中会有数字,并且会有一些我尚未确定的游戏功能。

通过一个简单的布尔值和一些 if 逻辑,我确定第一个单元格必须来自左列,但现在我无法确保每个后续单元格都与突出显示的单元格相邻。我为表格中的每个 td 分配了一个编号 id,从 1 到 49(7 行,每行 7)。当用户选择一个单元格时,我会在一个名为 cellCoord 的数组中捕获该单元格的 id。我希望这样的事情可能会奏效:

var thisCell = parseInt($(this).attr('id'));
if  (thisCell == (cellCoord[i]+1) || thisCell == (cellCoord[i]-1) ||
     thisCell == (cellCoord[i]+7) || thisCell == (cellCoord[i]-7))

不幸的是,它没有。有什么建议么?

我的努力的早期草稿可以在这里找到。

4

3 回答 3

1

从您的网站上获取表格,我会对其进行一些更改,添加课程

<table>
    <tr class="row">
        <td class="square candidate"></td>
        <td class="square"></td>
        <td class="square"></td>
        <td class="square"></td>
        <td class="square"></td>
        <td class="square"></td>
        <td class="square"></td>
    </tr>
    ...
</table>

CSS:

.square {
    width: 30px;
    height: 30px;
    border: white solid 1px;
    background-color: lightblue;
}

.highlighted {
    background-color: lime;
}

然后选择相邻的方块

$('.square').click(function () {
    if ($(this).hasClass('candidate')) {
        $(this).addClass('highlighted');
        // select adjacent squares
        // horizontal
        $(this).prev('.square').addClass('candidate');
        $(this).next('.square').addClass('candidate');
        // vertical
        var i = $(this).index();
        $(this).parent('.row').prev('.row').children(':eq(' + i + ')').addClass('candidate');
        $(this).parent('.row').next('.row').children(':eq(' + i + ')').addClass('candidate');
    }
});

一个正方形是 a .candidate,如果它与一个已经存在的.highlighted正方形相邻。

于 2013-02-22T22:14:35.860 回答
0

jQuery 的.index()功能可以为您解决这个问题。它可以告诉您在一组项目中选择了哪个项目。

http://api.jquery.com/index/

于 2013-02-22T21:45:35.873 回答
0

为每个单元格分配一个 x 和 y 坐标。此外,添加一个类“选定”做任何突出显示的 div。例如。

<div data-x="1" data-y="1"><div data-x="2" data-y="1">
<div data-x="1" data-y="2"><div data-x="2" data-y="2">

然后像下面这样。

var div = $('#idOfDivJustClicked');
var x = div.data('x');
var y = div.data('y');

然后使用 jquery 的 attr 选择器搜索包含正负一的 x 或 y 坐标的 div。这不是确切的逻辑,您需要实现类似的东西。

if ($('div[data-x=' + (x+1) + '][data-y=' + y + ']').hasClass('selected'))
{
    // found an adjacent highlighted cell
    // execute code
}
于 2013-02-22T21:46:05.513 回答