问题
I have been developing some sorting and selecting functions on a table and I found it very difficult to orient in a table with colspanned cells. I simply added the spanned cells and hid them. It looks good, it works with my js, great for indexing, but I would like to know if that is a legit approach.
.stuffing {
display: none;
}
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td colspan="3">1</td>
<td class="stuffing"></td>
<td class="stuffing"></td>
<td>4</td>
</tr>
</table>
document.querySelectorAll('table tr:nth-child(1) td')[3].innerHTML // "4"
document.querySelectorAll('table tr:nth-child(2) td')[3].innerHTML // "4"
If it wasn't for the hidden cells, I would have to access the value by [1].
The jQuery tablesorter iteself doesn't sort properly on tables with colspan.
Some tags to help people find this issue.
Retrieve “correct” index of table affected by colspan or rowspan.
Find each table cell's “visual location”.
回答1:
Your technique certainly improves programmatic access to tables having colspans.
If your colspan length is limited, you could avoid using hidden classes like this:
td[colspan="2"]+td,
td[colspan="3"]+td, td[colspan="3"]+td+td,
td[colspan="4"]+td, td[colspan="4"]+td+td, td[colspan="4"]+td+td+td {
display: none;
}
This throws an error in Safari:
document.querySelectorAll('table tr:nth-child(2) td')[3].innerHTML
This is resolved by indexing directly into the table using the rows and cells collections (both 0-based):
var tb= document.querySelector('table');
tb.rows[0].cells[3].innerHTML; //4
tb.rows[1].cells[3].innerHTML; //4
回答2:
If it is working properly that means that solution is okey. For sure it is not nice but sometimes you have to do things like that, some workarounds... But you should check it on different browsers and different versions of them to be sure that It will work for most of users. If site should work on mobile devices you should check it out too.
And you should think about one thing too. That more clever users will be able to remove this class in the code so you should think about it and check if it can be dangerous for you or not...
Maybe better approach would be to give your "tds", some Ids or classes. You can grab Tds in Jquery by last() function. Maybe you can do it in different way. I have to less informations to be able to think about different proper solution.
来源:https://stackoverflow.com/questions/30301967/is-it-bad-to-supplement-colspanned-table-with-hidden-cells