繁体   English   中英

获取父元素位置的jQuery索引

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

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

看起来jQuery的索引函数应该可以工作,无论传递的参数是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>

您只需要:

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

如果你想要td的索引

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

或者tr

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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