2011-08-25 97 views
1
<table> 
<tr onClick = "alert(this.FirstTDValue);" > 

    <td>123</td> 
    <td>Hello</td> 
    <td>Goodbye</td> 

</tr> 
</table> 

如何完成this.FirstTDValue以使alert將顯示'123',在TR或表級別請求它會有效嗎?如何使用此值從TD列中獲取價值

+0

我想你將不得不給第一​​的所以它知道在哪裏看,並從中取值。 – RSM

回答

5

錶行有一個細胞的集合,是細胞的活節點列表,所以:

alert(this.cells[0].textContent || this.cells[0].innerText); 

或許:

alert(this.cells[0].firstChild.data); 
3

<tr>元素有一個cells集合,讓你訪問子<td>元素:

this.cells[0].innerHTML

+0

捕捉!/* stuff */ – RobG

+0

This works too .. ..謝謝。 – bill

0

喜歡的東西...

<tr onClick = "getTD();" > 

<td>123</td> 
<td>Hello</td> 
<td>Goodbye</td> 

</tr> 
<script type="text/javascript"> 
function getTD(){ 
    alert(document.body.getElementsByTagName("td")[0]); 
} 

</script> 
+0

僅當這是頁面第一個表格中的第一行時纔有效。 –

0

這是我做的:

<script> 
Element.prototype.FirstTDValue = function() { 
    for (var i = 0; i< this.childNodes.length; i++) { 
     if (this.childNodes[i].tagName == 'TD') { 
      return this.childNodes[i].innerHTML; 
     } 
    } 
    return ("No TD Values"); 
} 
</script> 
<table> 
<tr onClick = "alert(this.FirstTDValue())" > 

    <td>123</td> 
    <td>Hello</td> 
    <td>Goodbye</td> 

</tr> 
</table> 
+0

您可以取代'children'的第一個元素,而不是遍歷'childNodes'。 –

+0

哇。而過度殺傷的獎去... – nnnnnn

+0

取決於* Element.prototype *支持值得一個......幸運逃脫。這次。 : - \ – RobG

0

jQuery的解決方案:

<tr onClick="alert($(this).children().first().text())" >