<table>
<tr onClick = "alert(this.FirstTDValue);" >
<td>123</td>
<td>Hello</td>
<td>Goodbye</td>
</tr>
</table>
How would this.FirstTDValue be accomplished so that alert would sh开发者_运维技巧ow '123', would it be efficient to request it at the TR or the Table level?
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() )" >
精彩评论