Check if each cell in a table is equal to the cell above
How do you check in JS what the value of the td above the current one is in a table? I'm trying to get开发者_JAVA技巧 a table like this:
|column1 | column2 | column3 | column4 |
----------------------------------------
| | | | |
----------------------------------------
| | | data | |
----------------------------------------
| | | data | fox |
----------------------------------------
| | bacon | | |
----------------------------------------
| | | | |
To look like this:
|column1 | column2 | column3 | column4 |
----------------------------------------
| | | | |
----------------------------------------
| | | | |
-------------------- data -----------
| | | | fox |
----------------------------------------
| | bacon | | |
----------------------------------------
| | | | |
My plan was to loop through each td element, to check the html of that td, then the one above, and if they are equal, hide the bottom one, and set the rowspan of the top one to 2.
I'm having trouble iterating through the td elements, I've tried some jQuery like this:
$("#myTable td").each(function(){
console.log($(this).html())
});
But I can't access easily the cell above/below the current one. Any ideas?
Maybe something like this:
$("#myTable td").each(function(){
var thisRowNum = $(this).closest('tr').prevAll().length;
var thisColNum = $(this).prevAll().length;
var cellAbove = $(this)
.closest('table')
.find('tr:eq('+thisRowNum+') td:eq('+thisColNum+')'); // the cell
var thisCell = $(this).html();
if (thisCell !== "") {
if ((thisCell === cellAbove.html())) {
$(this).hide();
cellAbove.attr("rowspan","2");
}
}
});
If you want do it, get the rows and cols and then create an array(a 2-D arraY of it and loop though it. It gives you much more flexibility. But I would say this job should be handled at the server side language you chose like JSP, ASP, PHP etc... that gives you much control.
You could write a traversal algorithm yourself, storing the values from row to row.
var above = [];
$('#myTable tr').each(function()
{
$(this).children('td').each(function(i)
{
if (above.length > i && $(above[i]).text() == $(this).text())
{
$(above[i]).attr('rowspan', ($(above[i]).attr('rowspan') || 1) + 1);
$(this).remove();
}
else
{
above[i] = this;
}
});
});
I didn't try it on an actual page, but in theory this should work:
<script type="text/javascript" charset="utf-8">
var container = ".mytable tbody > tr";
var td_index, row_index = 0;
$(container).each(function() {
td_index = -1;
row_index++;
if(row_index > 0) {
td_index ++;
var above_tr = $(container+"eq("+(row_index-1)+")");
var td_val = $(this).find("td:eq("+td_index+")").html();
var above_td_val = $(above_tr).find("td:eq("+td_index+")").html();
if(td_val == above_td_val) {
$(above_tr).find("td:eq("+td_index+")").attr("rowspan", 2);
$(this).find("td:eq("+td_index+")").remove();
}
}
});
</script>
精彩评论