获取父元素位置的jQuery索引

时间:2014-02-20 14:14:02

标签: javascript jquery

我有一个表格,其中单元格具有可点击区域。点击该区域时,我需要在其兄弟姐妹中获取父单元格的索引。

看起来jQuery's index function应该可以工作,无论传递的参数是jQuery对象还是DOM对象,但这些都不会在我的示例中返回预期的结果。

我在这里缺少什么想法?

这是我的例子:

<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>

2 个答案:

答案 0 :(得分:1)

你只需要:

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

答案 1 :(得分:1)

如果您想要td

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

tr

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

小提琴:http://jsfiddle.net/YBp8H/

相关问题