admin管理员组

文章数量:1279057

<table>
<tr  onClick = "alert(this.FirstTDValue);" >

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

</tr>
</table>

How would this.FirstTDValue be acplished so that alert would show '123', would it be efficient to request it at the TR or the Table level?

<table>
<tr  onClick = "alert(this.FirstTDValue);" >

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

</tr>
</table>

How would this.FirstTDValue be acplished so that alert would show '123', would it be efficient to request it at the TR or the Table level?

Share Improve this question asked Aug 25, 2011 at 0:35 billbill 1,1612 gold badges8 silver badges9 bronze badges 1
  • I imagine you would have to give the first <td> an id so it knows where to look and take the values from. – RSM Commented Aug 25, 2011 at 0:39
Add a ment  | 

5 Answers 5

Reset to default 6

Table rows have a cells collection that is a live NodeList of the cells, so:

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

Or perhaps:

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

<tr> elements have a cells collection that lets you access the child <td> elements:

this.cells[0].innerHTML

Something like...

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

This is how I did it:

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

jQuery Solution:

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

本文标签: javascriptHow to get value from TD column using thisvalueStack Overflow