javascript - 如何使用 jquery 查找 td 的最近相邻元素?

标签 javascript jquery

<分区>

我是 jquery 的新手,正在开发基于小 table 的游戏,我必须在 table 中找到 TD 周围的相邻元素。

例如:

1 2 3

4 5 6

7 8 9

表中有三行,如果我认为 5 是我的元素,那么如何找到 5 的相邻元素(邻居:2 4 6 8)???

最佳答案

为了完整性,没有 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]);
}

关于javascript - 如何使用 jquery 查找 td 的最近相邻元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20721908/

相关文章:

javascript - Heroku buildpack horse 忽略 package.json 中的 Node 版本

javascript - 使用lookAt在WebGL中创建旋转相机

javascript - 如何捕获 Select2 下拉菜单上的滚动事件?

javascript - Node/Grunt - Autoprefixer - 如何将配置添加到我的 Gruntfile.js 以及如何检查支持的浏览器?

javascript - 在 Internet Explorer 中旋转时钟指针

javascript - 准备好文档上的窗口滚动位置

javascript - 使用 $.trim 删除字符串中间的空格?

javascript - 使用 JQuery 选择器选择元素的父元素

jQuery UI 对话框手动关闭

asp.net - jQuery 自动完成在 AutoPostBack 上丢失文本