我有一个表格,其中单元格具有可点击区域。单击该区域时,我需要获取父单元在其同级之间的索引。

看起来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>

最佳答案

如果要td的索引

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


tr

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


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

08-18 03:38
查看更多