我是jquery的新手,我正在开发基于小桌面的游戏,我必须在桌面上找到TD周围的相邻元素。
EX:
1 2 3
4 5 6
7 8 9
表中有三行,如果我认为5是我的元素那么如何找到5的邻居元素(邻居:2 4 6 8)???
答案 0 :(得分:4)
为了完整性,没有jQuery:
var row = cell.parentNode;
var table_body = row.parentNode;
var neighbors = [];
if (cell.cellIndex > 0) {
neighbors.push(rows.cells[cell.cellIndex - 1]);
}
if (row.rowIndex > 0) {
neighbors.push(table_body.rows[row.rowIndex - 1].cells[cell.cellIndex]);
}
if (cell.cellIndex < rows.cells.length - 1) {
neighbors.push(rows.cells[cell.cellIndex + 1]);
}
if (row.rowIndex < table_body.rows.length - 1) {
neighbors.push(table_body.rows[row.rowIndex + 1].cells[cell.cellIndex]);
}
答案 1 :(得分:1)
这对于垂直邻居来说并不需要太多,但是你需要索引5(这是1) - 假设$(this)
表示包含{td
的{{1}} 1}}:
5
答案 2 :(得分:1)
我们可以使用next, prev
之类的遍历方法和eq
之类的选择方法以及add
来开发解决方案
var $td = $('table tr:eq(1) td:eq(1)'); //current td = 5
var index = $td.index(), $tr =$td.parent();
var $nbrs = $td.prev().add($td.next()).add($tr.prev().find('td').eq(index)).add($tr.next().find('td').eq(index));
console.log($nbrs.get())
演示:Fiddle
更详细的方法
var $td = $('table tr:eq(1) td:eq(1)'); //current td = 5
var index = $td.index(), $tr =$td.parent();
var $nbrs = $td.prev(); //find the previous td
$nbrs = $nbrs.add($td.next());//find the next td
$nbrs = $nbrs.add($tr.prev().find('td').eq(index));//find the td with the same index in previous row
$nbrs = $nbrs.add($tr.next().find('td').eq(index));//find the td with the same index in next row
$nbrs.css('color', 'red')
console.log($nbrs.get())
答案 3 :(得分:0)
我假设你在click
事件
你可以
4 by,
$(this).prev().text()
5 by,
$(this).next().text()
2 by,
$(this).closest('tr').prev().find('td').eq($(this).index()).text()
8 by,
$(this).closest('tr').next().find('td').eq($(this).index()).text()
但请记住,如果您点击边缘,代码可能会返回undefined
。