假设得到行ID在表中,这是我的表:如何从行索引使用JavaScript
<table>
<tr id="a">
<TD>a</TD>
</tr>
<tr id="b">
<TD>b</TD>
</tr>
</table>
我如何使用行指数从表中获取行ID?
上面只是一个例子,其中id是静态的,但在我的情况下,我的id是动态的,所以我不能使用 document.getElementById()
。
假设得到行ID在表中,这是我的表:如何从行索引使用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"
答案已经被编辑 有了CSS3,你可以使用第n个孩子 selctor。下面的例子显示的rowIndex = 2
alert(document.querySelector("table tr:nth-child(2)").id);
在jQuery中你可以用
alert($("table tr:nth-child(2)").attr('id'));
做同样的语法第n个孩子()可以在CSS中使用
<style>
tr:nth-child(2) {
color: red;
}
</style>
即使使用动态ID,它仍然可以工作。 –
'table.tr [1] .id' - >'b'? –
@MarcB它应该是'table.rows'而不是'table.tr' – Dennis