Toggle table row siblings
I have a table structured like this:
<table>
<tr id="id1" class="parent"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>
<tr class="id1"></tr>
<tr id="id2" class="parent"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>
<tr class="id2"></tr>
.....etc
</table>
As you can see child classes are coresponding to their parent id开发者_StackOverflow社区. Now I want to toggle all the rows which have class names equal to their parent row id whenever parent row is clicked.
I have tried this, perhaps stupid try:) and can't seem to get this working:
$('tr.parent').click(function() {
//alert('yay');
var tog = $(this).attr('id');
$(this).siblings().hasClass(tog).slideToggle();
return false;
});
Thanks.
Almost there, here ya yo:
$('tr.parent').click(function() {
var tog = $(this).attr('id');
$(this).siblings('.' + tog).slideToggle();
return false;
});
.hasClass()
returns a boolean, it checks if an element has a class, you want to filter by the class. .siblings()
accepts a selector filter, see here for details.
If the child rows are always after like your example, you can make this a bit more efficient as a forward only lookup with .nextAll()
like this:
$('tr.parent').click(function() {
$(this).nextAll('.' + $(this).attr('id')).slideToggle();
});
Jquery code:
<script type="text/javascript">
$(document).ready(function () {
$('table').children('tbody').toggle(false);
$(".lnkToggle").bind('click', function () {
$(this).closest('table').children('tbody').toggle();
});
});
</script>
HTML Table:
<table class="table table-striped">
<thead>
<tr>
<th style="text-align: left; width: 250px;">
<i class="lnkToggle" title="Click to view cases"> + </i>
MOVIES
</th>
</tr>
</thead>
<tbody>
<tr>
<td>MATRIX</td>
</tr>
<tr>
<td>TOY STORY</td>
</tr>
<tr>
<td>THE GOONIES</td>
</tr>
</tbody>
</table>
精彩评论