问题描述:

I need to hide show Table row, but it appears I'm not targeting it properly:

$('.ShowHide').click(function(){

$(this).next('.hiddenTR').toggle();

});

Here's my HTML:

<table>

<tr>

<td><img src="img.gif" class="ShowHide"></td>

<td>text 1</td>

</tr>

<tr class="hiddenTR">

<td colspan="2">hidden text 1</td>

</tr>

<tr>

<td><img src="img.gif" class="ShowHide"></td>

<td>text 2</td>

</tr>

<tr class="hiddenTR">

<td colspan="2">hidden text 2</td>

</tr>

</table>

Is it even possible to target like this? I need to show only the TR below and I do not know how many there could be, so using IDs is out of the question.

Need a nudge in the right direction.

Thanks.

网友答案:

If you try to hide the next tr node use:

$('.ShowHide').click(function(){
    $(this).closest('tr').next('.hiddenTR').toggle();
});

reference: .closest()

网友答案:

Try:

$('.ShowHide').click(function(){
    $(this).parents('tr').next('.hiddenTR').toggle();
});
网友答案:

To expand on the examples already given, depending on how many rows will be in the table, you should bind the click event to the table itself and "listen" for the element (node) that the click event originated from. This could drastically speed up your js.

Here's an example of this: http://jsfiddle.net/nEEwq/

Hope this helps!

相关阅读:
Top