Javascript jQuery:垂直获取下一个表单元格
如何使用jQuery访问传统网格布局htmlJavascript jQuery:垂直获取下一个表单元格,javascript,jquery,html,Javascript,Jquery,Html,如何使用jQuery访问传统网格布局html表中给定单元格正下方的单元格(td)(即,所有单元格恰好跨一行和一列的单元格) 我知道以下内容会将nextCell设置到单击单元格右侧的单元格,因为它们是直接同级,但我正在尝试检索单击单元格正下方的单元格: $('td').click(function () { var nextCell = $(this).next('td'); }); 最好我不使用任何类或ID。每个表行中是否有相同数量的单元格?如果是这样,您可以获得相关单元格的“计数”,
表中给定单元格正下方的单元格(td
)(即,所有单元格恰好跨一行和一列的单元格)
我知道以下内容会将nextCell
设置到单击单元格右侧的单元格,因为它们是直接同级,但我正在尝试检索单击单元格正下方的单元格:
$('td').click(function () {
var nextCell = $(this).next('td');
});
最好我不使用任何类或ID。每个表行中是否有相同数量的单元格?如果是这样,您可以获得相关单元格的“计数”,然后在下一步('tr')
中选择相应的单元格
$("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 nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
index
是当前行中单元格的基于0的索引(prevAll
查找此行之前的所有单元格)
然后在下一行中,我们在索引+1处找到n个子项
td(n个子项
从1开始,因此+1
)。如果不使用选择器,可以执行以下操作:
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);
//...
});
函数GetNextCellVertical(htmlCell){
//查找此单元格的位置。。
var$row=$(htmlCell.parent();
var cellIndex=$.inArray(htmlCell,$row[0].cells);
var table=$row.parent()[0];
var rowIndex=$.inArray($row[0],table.rows);
//垂直获取下一个单元格。。
返回(rowIndex
效率在这里并不重要,但像这样做要快得多——在超过100000次迭代的测试中,它比基于选择器的方法快2-5倍。为什么
$(this).prevAll().length
超过$this.index()
?@JustinSatyr我直到现在都不知道索引。:)我从未想过使用.prevAll().length。哈哈。同样的结果,我不知道哪一个更快。@JustinSatyr我修正了索引+1
。另外,也许index
调用了相同的东西prevAll
,因此我认为它们在性能方面非常相似,index
更容易理解。@JustinSatyr实际上,这正是jquery在$.fn.index()
方法的核心中使用的语法。使用prevAll
可能会加快几十万次迭代,但最终.index()
更易于阅读/维护。您不需要将'td'
参数用于子级,如果OP已在表中,则可能会将其丢弃。
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);
//...
});