2014-11-14 36 views
0

我正在開發一款網頁遊戲,並且需要檢查表格上的哪些單元格已被用戶選中。現在我只是檢查行和細胞指數值:使用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做這個的?

+1

能更好地滿足於http://codereview.stackexchange.com/ – 2014-11-14 16:04:38

+0

@StéphaneBruckert我不是要求一個代碼審查,雖然。我問我是否可以使用jQuery從表中獲取行和單元格索引。 – 2014-11-14 16:06:38

+0

您可以使單元格爲複選框或使標籤與複選框相關聯,然後序列化它們並將其與具有正確值的字符串進行比較。 – 2014-11-14 16:12:32

回答

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

相關問題