如何使用 JavaScript 从表中的行索引中获取行 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13746153/
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-24 12:47:56  来源:igfitidea点击:

How to get row id from row Index in table using JavaScript

javascripthtml

提问by Prateek

Suppose this is my table:

假设这是我的表:

<table>
    <tr id="a">
       <TD>a</TD>
    </tr>
    <tr id="b">
       <TD>b</TD>
    </tr>
</table>

How can I get row id using the row index from a table?

如何使用表中的行索引获取行 ID?

Above is just an example where id is static but in my case my id is dynamic, so I can't use document.getElementById().

上面只是一个例子,其中 id 是静态的,但在我的情况下,我的 id 是动态的,所以我不能使用 document.getElementById().

回答by Cerbrus

Assuming you have only one table on your page:

假设您的页面上只有一张表格:

document.getElementsByTagName("tr")[index].id;

Preferablythough, you'd give your tablea id, though, and get your row like this:

最好不过,你给你的table一个id,不过,让你的行这样的:

<table id="tableId">
    <tr id="a">
        <td>a</td>
    </tr>
    <tr id="b">
        <td>b</td>
    </tr>
</table>
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);

This way, you can be certain you don't get any interference, if you have multiple tables in your page.

这样,如果您的页面中有多个表,您就可以确定不会受到任何干扰。

回答by I Hate Lazy

"So, How can i get row id using row Index from a table"

“那么,如何使用表中的行索引获取行 ID”

You would select the table, and use the .rowsproperty to get the row by index.

您将选择table,并使用该.rows属性按索引获取行。

var table = document.getElementsByTagName("table")[0]; // first table

var secondRow = table.rows[1]; // second row


Then you just get the ID in the typical manner.

然后,您只需以典型方式获取 ID。

console.log(secondRow.id); // "b"

DEMO:http://jsfiddle.net/MErPk/

演示:http ://jsfiddle.net/MErPk/

回答by Eystein Bye

Answer has been editedWith CSS3 you can use the nth-childselctor. Here the example shows the rowIndex = 2

答案已编辑使用 CSS3,您可以使用nth-child选择器。这里的例子显示了 rowIndex = 2

 alert(document.querySelector("table tr:nth-child(2)").id);

In jQuery you can do this with

在 jQuery 中,您可以使用

 alert($("table tr:nth-child(2)").attr('id'));

The same syntax nth-child()can be used in CSS

可以在 CSS 中使用相同的语法nth-child()

<style>
    tr:nth-child(2) {
        color: red;
    }
</style>