2012-12-06 21 views
3

假设得到行ID在表中,这是我的表:如何从行索引使用JavaScript

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

我如何使用行指数从表中获取行ID?

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

+1

即使使用动态ID,它仍然可以工作。 –

+2

'table.tr [1] .id' - >'b'? –

+2

@MarcB它应该是'table.rows'而不是'table.tr' – Dennis

回答

6

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

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); 

这种方式,你可以肯定你没有得到任何干扰,如果你在你的页面的多个表。

3

“所以,我怎么能使用行指数从表中获取行ID”

你会选择table,并使用.rows财产指标得到该行。

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

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

然后你刚才得到的ID的典型方式。

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

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

2

答案已经被编辑 有了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> 
+0

为什么在获取表格行这么简单的事情上使用jQuery? – Cerbrus

+0

只是一个例子来显示nth-child(也是一个CSS选择器)是如何工作的。 –

+0

不够公平,但你可能想提一下[jQuery的可怕程度如何慢](http://jsperf.com/table-row-native-vs-jquery)。 – Cerbrus

相关问题