본문으로 바로가기

예시 소스는 다음과 같다. 


#jquery

$('.clickBtn').bind('click', function() {
            var trNum = $(this).closest('tr').prevAll().length;
            console.log('trNum : ' + trNum);
        });
#html


<table>
    <tr>
        <td>
            0
        </td>
        <td>
            <button type="button" class="clickBtn">Click!</button>
        </td>
    </tr>

    <tr>
        <td>
            1
        </td>
        <td>
            <button type="button" class="clickBtn">Click!</button>
        </td>
    </tr>

    <tr>
        <td>
            2
        </td>
        <td>
            <button type="button" class="clickBtn">Click!</button>
        </td>
    </tr>

    <tr>
        <td>
            3
        </td>
        <td>
            <button type="button" class="clickBtn">Click!</button>
        </td>
    </tr>
</table>

- closest 함수 :  this 엘리먼트의 가장 가까운 tr을 탐색

- prevAll 함수 : this 엘리먼트의 가장 가까운 tr 이전의 tr들을 가져와서 객체로 만들어 반환한다


참고사이트 :

http://findfun.tistory.com/226

http://ismydream.tistory.com/94