How to hide a row that containing more than one empty cell?
For the table below, row2 and row3 have more than 1 empty cell(<td></td>
), how can I use jQuery to check if each row in the table have more than 1 empty cell, than hide that row accordingly?
UPDATED:
If I want to check if each row(td) contain more than ONE cell(td) that is containing JUST witespace, than hide that row?
Thanks
<table>
<tr class="row1">
<td>a</td>
<td>b</td>
<td>c</td>
<td>d</td>
</t开发者_开发技巧r>
<tr class="row2">
<td>a</td>
<td>b</td>
<td></td>
<td></td>
</tr>
<tr class="row3">
<td></td>
<td></td>
<td>c</td>
<td></td>
</tr>
...
<tr class="row100">
<td>a</td>
<td>b</td>
<td>c</td>
<td></td>
</tr>
</table>
How can I use jQuery to check if each row in the table have more than 2 empty cell, than hide that row accordingly?
You can use filter()
.
$('table tr').filter(function() {
return $(this).children('td:empty').length > 2;
}).hide();
jsFiddle.
Update
If I want to check if each row(td) contain more than ONE cell(td) that is containing JUST whitespace, than hide that row?
I think this is what you now want...
$('table tr').filter(function() {
var valid = $(this).children('td').filter(function() {
return ! $(this).text().replace(/\s/g, '').length;
}).length;
return valid > 1;
}).hide();
jsFiddle.
In actual use, "empty" cells often contain all kinds of whitespace. EG: <td> </td>
, <td> \n </td>
, <td> </td>
, <td class="Invalid"></td>
, etc.
See how easy it is to break?
A more robust solution handles real-life HTML:
$('table tr').filter ( function () {
var blankCells = $(this).html ().match (/<td[^<>]*>(?:\s| )*<\/td>/ig);
var numBlank = blankCells ? blankCells.length : 0;
return numBlank > 1;
} ).hide ();
See the demo at jsFiddle.
Note that this solution is probably fine for most practical cases, but since it uses regex to parse the DOM (even a little), it could end up showing extra rows if the HTML was coded poorly.
$("tr").each(function() {
var i = 0;
$(this).children("td").each(function() {
if (!$(this).html()) {
i++;
}
if (i > 2) {
$(this).parent().hide();
return false;
}
});
});
jsfiddle: http://jsfiddle.net/fT9VQ/1/
Alex's answer is probably better.
精彩评论