简体   繁体   中英

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

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?

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:

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. However you can use the condition you want to get the list of marked cells.

See small demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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