Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

How to find the index of a row in a table using jquery

I'm trying to find the index of a row in a table. I'm trying to use the following code, but I seem to get an index of -1.

$(document).ready(function()
{
    $("tr").click(function (){
        var index = $("table").index($(this));
        $("span").text("That was row index #" + index);
    });
});

With html that looks like this;

<table>
<tbody>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
    <tr><td>click</td></tr>
</tbody>

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried:

$("tr").index(this)

The documentation shows just passing this and that the preceding selection should be where the node is found. If you need to find it in a specific table (and there are multiple), you may need to provide some context:

// haven't tested this
$("tr", $(this).closest("table")).index(this) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...