jQuery:垂直获取下一个表格单元格
jQuery: Get next table cell vertically
如何使用jQuery访问传统网格布局html table
中给定单元格下方的单元格(td
)?
我知道以下内容会将nextCell
设置为单击单元格右侧的单元格,因为它们是直系兄弟,但我正在尝试检索单击单元格下方的单元格:
$('td').click(function () {
var nextCell = $(this).next('td');
});
我最好不使用类或id。
试试这个:
$("td").click(function(){
// cache $(this);
var $this = $(this);
// First, get the index of the td.
var cellIndex = $this.index();
// next, get the cell in the next row that has
// the same index.
$this.closest('tr').next().children().eq(cellIndex).doSomething();
});
$('td').click(function () {
var index = $(this).prevAll().length
var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});
index
是当前行中单元格的基于0的索引(prevAll
查找该单元格之前的所有单元格)。
然后在下一行中,我们在索引+1处找到nth-child
td(nth-child
从1开始,因此是+ 1
)。
怎么样:
$('td').click(function () {
var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
如果你想在不使用选择器的情况下完成,你可以执行:
function getNextCellVertically(htmlCell){
//find position of this cell..
var $row = $(htmlCell).parent();
var cellIndex = $.inArray(htmlCell, $row[0].cells);
var table = $row.parent()[0];
var rowIndex = $.inArray($row[0], table.rows);
//get the next cell vertically..
return (rowIndex < table.rows.length-1) ?
table.rows[rowIndex+1].cells[cellIndex] : undefined;
}
$('td').click(function () {
var nextCell = getNextCellVertically(htmlCell);
//...
});
效率在这里并不重要,但这样做会更快——在超过100000次迭代的测试中,它比基于选择器的方法快2-5倍。
每个表行中的单元格数量是否相等?如果是,您可以获得有问题单元格的"计数",然后在next('tr')
中选择相应的单元格。
相关文章:
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- 如何将jQuery/AAJAX结果放入表格单元格
- 使用下拉选择菜单高亮显示一行表格单元格
- 使用javascript下拉菜单更改表格单元格的颜色
- 表格单元格高度与背景高度匹配
- 在表格单元格中查找超链接
- 如何使用单击属性和工具提示动态创建表格单元格,该工具提示将超链接到页面
- 在 DIV 中定位表格单元格
- 单击时将表格单元格从范围更改为输入
- 使用 javascript 为 HTML 表格单元格指定颜色
- 将单击表格单元格重定向到其中的
- JQuery insertAfter();移动下一个表格单元格
- 单击并用CTRL+C复制值时高亮显示html表格单元格
- TinyMCE - 允许表格单元格元素作为有效的 html
- 使用jsp更改表格单元格的颜色
- 如何从表格单元格中删除html的某些部分
- 在动态表格单元格跨度中单击时更新一个权重值
- 从所选内容中选择选项,并在表格单元格中显示所选内容的信息
- 在输入字段之前提取表格单元格中的文本
- 使用外部 javascript 更改多个表格单元格中的文本