获取表中单元格的列索引和行索引

时间:2015-02-12 09:45:49

标签: javascript

在JS中,如何检索列&行索引;给定单元格索引,宽度(colCount)&表的高度(rowCount)?

例如

var cellIndex = 11;
var colCount = 3;
var rowCount = 5;

| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
|10 | X |12 |
|13 |14 |15 |

//should return
colIndex = 2;
rowIndex = 4;

例如

var cellIndex = 8;
var colCount = 4;
var rowCount = 4;

| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | X |
| 9 |10 |11 |12 |
|13 |14 |15 |16 |

//should return
colIndex = 4;
rowIndex = 2;

谢谢!

1 个答案:

答案 0 :(得分:2)

指数的计算方法如下。

rowIndex = ( ( cellIndex - 1 ) / colCount ) + 1;
colIndex = ( ( cellIndex - 1 ) % colCount ) + 1;

请注意,计算不需要rowCount