使用jQuery获取表行和单元格

时间:2014-11-14 16:00:15

标签: javascript jquery

我正在开发网页游戏,需要检查用户选择了桌面上的哪些单元格。现在我只是检查行和单元格索引值:

的JavaScript

function checkForWin() {
    var card = document.getElementById('card');
    if ((card.rows[0].cells[0].marker && // 1st row
        card.rows[0].cells[1].marker &&
        card.rows[0].cells[2].marker &&
        card.rows[0].cells[3].marker &&
        card.rows[0].cells[4].marker)) {
        youWin();
    } else {
        noWin();
    }
}

用jQuery做这个更优雅吗?

2 个答案:

答案 0 :(得分:2)

做一些循环:

function checkForWin() {
var card = document.getElementById('card');
var win = true;
for (var i = 0; i < card.rows[0].cells.length; i++){
    if(!card.rows[0].cells[i])
       win = false;
}
if(win)
  youWin();
else
  noWin();
}

答案 1 :(得分:0)

使用jQuery,您可以迭代标记单元格列表,或者只获取标记单元格列表:

var marked = $('#cards td.marked');
// If you have a special way to detect a cell is marked that 
// needs more custom test than checking the class you can use .filter.
// Just as example I use the same condition.
//var marked = $('#cards td').filter(function () {
//    return $(this).hasClass('marked');
//});


// If you want to just iterate the selected cells.
marked.each(function () {
    var i = $(this).closest('tr').index();
    var j = $(this).index();
    console.log(i, j);
});

// If you want to the the array of selected cells.
var indexes = marked.map(function () {
    return {
        i: $(this).closest('tr').index(),
        j: $(this).index()
    };
}).get();

为了更容易,我假设marked类的单元格表示标记的单元格。但是,您可以使用您想要获取标记单元格列表的条件。

查看小demo