I have a structure that looks like this:
<div class="project_group">
<table>
<tr style="display:none">
<td>...</td>
</tr>
<tr style="display:none">
<td>...</td>
</tr>
<tr>
<td>...</td>
</tr>
</table>
</div>
I have many different project_group div
s in the page. Now, I want to iterate over each of these divs and get a count of the visible tr
s. If the count is 0, then I want to hide the whole div.
$('div.project_group').each(function(index){
if ($(this)[index].filter('table tr:visible').length > 0)
{
$(this)[index].show();
}
else
{
$(this)[index].hide();
开发者_运维百科 }
})
The error message I get:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'filter'
Use the find()
[docs] method if you don't have nested tables.
$(this).toggle( $(this).find('tr:visible').length );
...and I used the toggle()
[docs] method to show or hide based on whether or not any matches were found. 0
means hide
, greater than 0
means show
.
How about a one liner:
$('div.project_group').not(':has(tr:visible)').hide();
There is no need to use [index]
here, and use .find
instead of .filter
:
$('div.project_group').each(function(index){
if ($(this).find('table tr:visible').length > 0)
$(this).show();
else
$(this).hide();
})
精彩评论