简体   繁体   English

使用jQuery获取表行和单元格

[英]Get table rows and cells with jQuery

I'm working on a web game and need to check for which cells on the table have been selected by the user. 我正在开发一款网络游戏,需要检查用户是否已选择表格中的哪些单元格。 Right now I'm just checking for the row and cell index value: 现在,我只是在检查行和单元格索引值:

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

Is there a more elegant of doing this with jQuery? 使用jQuery这样做是否更优雅?

Just make some loop : 只是做一些循环:

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

Using jQuery you could iterate over the list of marked cells or just get the list of marked cells like this: 使用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();

To make it easier I assumed that a cell with the marked class means a marked cell. 为了简化起见,我假设带有marked类的单元格意味着一个标记单元格。 However you can use the condition you want to get the list of marked cells. 但是,您可以使用要获取已标记单元格列表的条件。

See small demo 观看小样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM