简体   繁体   中英

jQuery's index to get the position of a parent element

I have a table where cells have a clickable area. When clicking on that area, I need to get the index of the parent cell among its siblings.

It looks like jQuery's index function should work regardless of the parameter passed being a jQuery object or a DOM object, but none of these return the expected result in my example.

Any ideas what I'm missing here?

This is my boiled down example:

<table>
    <tbody>
        <tr>
            <td><span class="a">Apricot</span></td>
            <td><span class="b">Banana</span></td>
            <td><span class="c">Cherry</span></td>
        </tr>
    </tbody>
</table>

<script src="http://code.jquery.com/jquery-1.10.2.min.js"/></script>
<script>
    $('span').click(function(){
        var jq_closestCell = $(this).closest('.td');
        var dom_closestCell = jq_closestCell[0];

        var jq_arrayCells = $('table tr td');
        var dom_arrayCells = jq_arrayCells[0];

        // This returns -1:
        console.log( jq_closestCell.index(dom_arrayCells) );

        // This returns -1:
        console.log( jq_closestCell.index(jq_arrayCells) );

        // Just for completeness, these obviously return
        // an error ("Uncaught TypeError: Cannot call method 'index' of undefined")
        console.log( dom_closestCell.index(dom_arrayCells) );
        console.log( dom_closestCell.index(jq_arrayCells) );
    });
</script>

You just need:

$('span').click(function () {
    var jq_closestCellIndex = $(this).closest('td').index();
    console.log(jq_closestCellIndex );
});

If you want the index of the td

var tdIndex = $(this).closest("td").index();

Or the tr

var trIndex = $(this).closest("tr").index();

Fiddle: http://jsfiddle.net/YBp8H/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM