获取td的节点索引

时间:2012-02-11 04:59:34

标签: jquery indexing html-table

如果我有一个像下面那样的身体...我知道如果我点击第一个收音机它会返回1.如果我点击表格外面的那个它返回2.但是当我点击第一个嵌套表格时td它在两个警报中返回其索引加上'parent's td索引。如何只返回嵌套的td索引,该索引应为2?这只是一个动态构建的示例表结构,因此它几乎可以与任何表设计和任何td一起使用。

有什么建议吗? 这是我用来在用户点击td时返回索引的代码(我为输入,textarea等捕获其他索引):

        $("td").click(function (event) {
            var nodeIndex = $("td").index();
            var nodeName = $(this).get(0).nodeName
            alert(nodeName + "," + nodeIndex);
        });

这是样本正文:

<body>  
    <input type="radio" />
        <table class="parent_table">
            <tr>
                <td>
                    <table class="nested_table">
                        <tr>
                            <td>
                                Sample Text</td>
                            <td>
                                &nbsp;</td>
                        </tr>
                    </table>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
       <input type="radio" />
    </body>

3 个答案:

答案 0 :(得分:0)

这是罪魁祸首,它调用所有<td> s

var nodeIndex = $("td").index();

替换为:

var nodeIndex = $(this).index();

答案 1 :(得分:0)

表格cellIndex上已经有了方便的属性tdrowIndex上有tr。这意味着您不需要使用jQuery。

相反,尝试这样的事情(无论如何更有效率):

// set ID "parent_table" on the parent table, then...
document.getElementById('parent_table').onclick = function(e) {
    e = e || window.event;
    var t = e.srcElement || e.target;
    while( t != this && (!t.tagName || t.tagName != "TD")) t = t.parentNode;
    if( t.tagName == "TD") {
        alert("You clicked on cell number "+t.cellIndex+" in row number "+t.parentNode.rowIndex);
    }
}

除了提高效率之外,它还避免了让jQuery通过的混乱。当您在代码中单击嵌套的TD时,您实际上是在单击父表的TD以及嵌套的TD,因此您会收到两个警报。在这里,你只会得到一个。

答案 2 :(得分:0)

解决。我只是将td放入全局点击,然后能够在一个消除双重警报的事件中记录节点名和索引....

jQuery('td').live('click', function (event) {

    if (event.target.nodeName.toLowerCase() == "td") {
        var nodeIndex = $("td").index(this);
        var nodeName = $(this).get(0).nodeName
        alert(nodeName + "," + nodeIndex); 
    }

});
相关问题