如何使用jQuery在表格中从水平到垂直重新分配Tab键顺序?

如何使用jQuery设置带有输入元素的表的Tab键顺序,以便tab-order是垂直的(在每个列下面)而不是默认的水平方法?

下面的数字代表了我想要的标签顺序。 我让jQuery代码独立于表中的行数和列数工作。

示例表 (遗憾地呈现为图像)

Picture 1.png http://img263.imageshack.us/img263/9125/picture1pjf.png

示例表HTML代码:

这是一种方法:

 $(function() { $('tr').each(function() { // For each row $(this).find('td').each(function(i) { // For each cell in that row (using i as a counter) $(this).find('input').attr('tabindex', i+1); // Set the tabindex of each input in that cell to the counter }); // Counter gets reset for every row }); }); 

这实现了这样的事情:

1 2 3 4 5

1 2 3 4 5

1 2 3 4 5

因此,通过tabbing,你首先要经历所有的,然后是所有的两个,依此类推。

示例: http : //jsfiddle.net/grc4/G5F7S/3/

编辑:

要在存在其他输入字段时避免此问题,您只需向每个tabindex添加偏移量即可。 这并不总能使订单完美,但总比没有好。

更新的示例如下: http : //jsfiddle.net/grc4/G5F7S/6/

如果你有矩形表,逻辑会更容易一些,但这里有一个解决方案应该处理任何情况:

 // Count the max number of columns in all rows of the table var maxRowCount = 0; // Set columnCount to the count of the row with the most cells // Loop through all rows in case some rows are larger than others $('table tr').each(function() { maxRowCount = Math.max(maxRowCount, $(this).children('td').length); }); // Number all of the cells in the table var cellCounter = 1; // Loop through the table, column first instead of row first for (var columnIndex = 0; columnIndex < maxRowCount; ++columnIndex) { // Loop through all the rows for the current column $('table tr').each(function() { // ...but only look at cells matching the current column var cellForCurrentColumn = $(this) .children('td') .eq(columnIndex) .find('input'); // Some rows could be bigger than others, // so cellForCurrentColumn might not exist for shorter rows if (cellForCurrentColumn != null) { // Set the tab index and then increment the counter cellForCurrentColumn.attr('tabindex', cellCounter++); } }); } 
  
column 1 column 2 column 3 column 4
row 1 1
5
row 2 2 (non-text input)
6
9
12
row 3 3
7 (multiple inputs)
10 (inline comment)
row 4 4
8 (disabled input)
11
13