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

cwd*_*cwd 11 jquery

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

下面的数字代表我想要的标签顺序.我使用jQuery代码独立于表中的行数和列数.

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

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

示例表HTML代码:

<table>
 <tr>
  <td><input type="text" /></td> <!-- 1 -->
  <td><input type="text" /></td> <!-- 4 -->
  <td><input type="text" /></td> <!-- 7 --> 
 </tr>
 <tr>
  <td><input type="text" /></td> <!-- 2 -->
  <td><input type="text" /></td> <!-- 5 -->
  <td><input type="text" /></td> <!-- 8 -->
 </tr>
 <tr>
  <td><input type="text" /></td> <!-- 3 -->
  <td><input type="text" /></td> <!-- 6 -->
  <td><input type="text" /></td> <!-- 9 -->
 </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

grc*_*grc 22

这是一种方法:

$(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
    });
});
Run Code Online (Sandbox Code Playgroud)

这实现了这样的事情:

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/

  • +1; (ab)使用HTML规范进行出价的好方法:)简单明了的代码. (2认同)