繁体   English   中英

如何使用JavaScript从表中的行Index获取行id

[英]How to get row id from row Index in table using JavaScript

假设这是我的表:

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

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

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

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

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

最好不过,你会给你的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);

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

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

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

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

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

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

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

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

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

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

在jQuery中,您可以使用

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM