![](/img/trans.png)
[英]Use JQuery to get all table cells between two table cells on different rows
[英]Get table rows and cells with 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這樣做是否更優雅?
只是做一些循環:
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();
}
使用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
類的單元格意味着一個標記單元格。 但是,您可以使用要獲取已標記單元格列表的條件。
觀看小樣
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.