jQuery 如何使用jquery查找表中行的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/469883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:12:18  来源:igfitidea点击:

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

jquery

提问by ilivewithian

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.

我正在尝试查找表中一行的索引。我正在尝试使用以下代码,但我似乎得到了 -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;

使用 html 看起来像这样;

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

Thanks

谢谢

回答by Rob

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) 

回答by Ates Goral

Try:

尝试:

var index = $("table tr").index(this);

The documentation for index()says:

的文档index()说:

Searches every matched element for the object and returns the index of the element, if found, starting with zero. If a jQuery object is passed, only the first element is checked.

搜索对象的每个匹配元素并返回元素的索引(如果找到),从零开始。如果传递了 jQuery 对象,则只检查第一个元素。

You need to call the index()on a collection of <tr>elements, not the parent <table>.

您需要index()<tr>元素集合上调用,而不是父<table>

回答by agwntr

Based on Robs answer to find index in specific table, this worked for me.

基于 Robs 在特定表中查找索引的答案,这对我有用。

var index = $('tr', $(this).closest("table")).index(this);

回答by Andrew

I've just found an interesting trick, which basically consists on counting the previous siblings:

我刚刚发现了一个有趣的技巧,它基本上包括计算以前的兄弟姐妹:

var tr = $(some_selector);
var rowIndex = tr.prevAll().length;

This way you will get 0 if this is the first tr, 3 if this is the 4th tr, etc.

这样,如果这是第一个tr,您将获得 0 ,如果这是第四个tr,则为 3,依此类推。

Just for the sake of it, another option using index(), which saves you from having to know how to select the containing table:

只是为了它,使用另一个选项index(),它使您不必知道如何选择包含表:

var rowIndex = tr.parent().children().index(tr);

回答by Poorna

Get the td object and its parent index is tr index

获取td对象,其父索引为tr index

$(this).parent().index()