I have a HTML table that contains both ROWSPANs and COLSPANs.
How can I find each cell's "visual location" using jQuery?
For example, here's a visual representation of my table with each cell populated with what the "visual location" algorithm should return:
(Note: I only really care about cells within the <tbody>
and the column reference can be an integer, not an alphabetic character, I've only done this to easily highlight the problem)
+--+--+--+--+--+
| |A |B |C |D |
+--+--+--+--+--+
|1 |A1|B1 |D1|
+--+--+--+--+ +
|2 |A2 |C2| |
+--+ +--+ +
|3 | |C3| |
+--+--+--+--+--+
|4 |A4|B4|C4|D4|
+--+--+--+--+--+
|XYZ |
+--+--+--+--+--+
I've tried implementing the first, however the reference for cell C3 is inaccurate as it doesn't take into account ROWSPANS. The second link may be able to be merged into the solution of the first, but I can't figure out how.
I'm hoping to use this as a function called getCellLocation(cell)
that will return an associative array that returns the location something like this:
function getCellLocation(cell)
{
var row_number = parseInt($(cell).parent().prevAll().length) + 1;
var col_number = 1;
$(cell).prevAll('td').each(function() {
col_number += $(this).attr('colspan') ? parseInt($(this).attr('colspan')) : 1;
});
var location = new Array();
location['row'] = row_number;
location['col'] = col_number;
location['index'] = $('td').index(cell) + 1;
return location;
}
$('table td').each(function(i){
var cell = getCellLocation($(this));
$(this).prepend('<span class="ref">R' + cell['row'] + ':C' + cell['col'] + ':D' + cell['index'] + '</span>');
});
Here's the HTML of the example table:
<table border="1" cellspacing="0">
<thead>
<tr>
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>A1</td>
<td colspan="2">B1</td>
<td rowspan="3">D1</td>
</tr>
<tr>
<th>2</th>
<td rowspan="2" colspan="2">A2</td>
<td>C2</td>
</tr>
<tr>
<th>3</th>
<td>C3</td>
</tr>
<tr>
<th>4</th>
<td>A4</td>
<td>B4</td>
<td>C4</td>
<td>D4</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">XYZ</td>
</tr>
</tfoot>
</table>
<style> span { background-color: #ffc; margin-right: .5em;} </style>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…