문제

I need to count the number of rows in a table. I need them to be counted as the user clicks an image inside a <td>

So far I've tried something like this:

$(".up, .down").click(function(){
var rows = $(this).closest('table').find('tr').length;
});

.up and .down are the class of the images clicked For practical reasons the table does not have an ID... It seems like it takes the first table - not the closest...

--- added ---

    <table class='bokse'><tr>
<tr sideid='7' sidepos='1'>
<td><h3 class='link' pid='7'>Formål</h2></td>
<td><img src='btn/op.png' class='up' title='ryk op' alt='op' /> <img src='btn/ned.png' class='down' title='ryk ned' alt='ned' /> <img src='btn/vis.png' class='vis' item='page_7' title='vis' alt='vis' /></td>
</tr>
<tr sideid='8' sidepos='2'>
<td><h3 class='link' pid='8'>Vedtægter</h2></td>
<td><img src='btn/op.png' class='up' title='ryk op' alt='op' /> <img src='btn/ned.png' class='down' title='ryk ned' alt='ned' /> <img src='btn/vis.png' class='vis' item='page_8' title='vis' alt='vis' /></td>
</tr>
<tr sideid='10' sidepos='3'>
<td><h3 class='link' pid='10'>Bliv medlem</h2></td>
<td><img src='btn/op.png' class='up' title='ryk op' alt='op' /> <img src='btn/ned.png' class='down' title='ryk ned' alt='ned' /> <img src='btn/vis.png' class='vis' item='page_10' title='vis' alt='vis' /></td>
</tr>
</table>

There are a series of tables like this with various lengths. Each is nested inside another table.

Though the number of rows varies, it says there are 4 rows - as in the first table - regardless of which I click

도움이 되었습니까?

해결책

That is because of an extra <tr> at the begnining. remove the first <tr> which does not have an end </tr>. <table class='bokse'><tr> See this http://jsfiddle.net/3PM9M/

$(".up, .down").click(function(){

    alert('total rows -' + $(this).parents('table').find('tr').length); //Gives all the tr's
    alert('Clicked row -' + (parseInt($(this).parents('tr').index()) + 1)); // clicked tr's index
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top