I have 2 tables, each of which is contained within different divs, similar to what we see here:
<div id="prices">
<table>
<tr class='hidden-row'>
<td>
<img class='expand-collapse-icon' />
</td>
</tr>
</table>
</div>
<div id="performance">
<table>
<tr class='hidden-row'>
<td>
<img class='.expand-collapse-icon' />
</td>
</tr>
</table>
</div>
I have some jQuery code that selects hides/shows some of the rows when you click the image. The problem is that it's showing rows from both tables, rather than the table the image exists in.
That's because of the way I'm selecting the rows:
$('.expand-collapse-icon').click(function() {
$(".hidden-row").toggle(); // it's finding all hidden rows in both tables.
});
I'm开发者_高级运维 having trouble selecting only the rows associated with the current table I've clicked. I tried identifying the specific div I'm in with this:
$('.expand-collapse-icon').parent('td').parent('tr').parent('table').parent('div')
but this doesn't work. It just returns a jQuery object with a length of 0, so it's obviously not finding the parent div. Is there a better way of me selecting only the rows that exist within the correct table?
This should work:
$('.expand-collapse-icon').closest('div');
Closest searches the dom-tree upwards for the next occurence of the selector.
all you need to do is this:
var element = $('.expand-collapse-icon').parents('div:eq(0)');
instead of
$('.expand-collapse-icon').parent('td').parent('tr').parent('table').parent('div')
use this
$(this).parent('td').parent('tr').parent('table').parent('div')
or
$(this).parent('td').parentNode.parentNode.parentNode
$('.expand-collapse-icon').click(function() {
var div = $(this).closest("div");
if (div.id == 'prices') {
// do X
} else {
// do Y
}
});
This should work either:
$('.expand-collapse-icon').click(function() {
$(this).parents('div').hide(); // it's finding clicked img's parent div and hiding it.
});
精彩评论