我找到了一个代码,它获取了点击的行数,但我无法理解。
任何人都可以解释以下代码吗?
<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
<tr><td>first row</td></tr>
<tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>
答案 0 :(得分:0)
// Binding a function to a onload event and invokes it when
// window is loaded
onload = function () {
// Checking if the 2 methods are supposted by the browser.
// If no thne it returns and does nothing
if (!document.getElementsByTagName || !document.createTextNode) return;
// Finding the table by id and get the `tbody` tag inside it
// The get all the tr's based on tagName
var rows = document.getElementById('my_table')
.getElementsByTagName('tbody')[0]
.getElementsByTagName('tr');
// Iterate over all rows and bind a click event
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function () {
alert(this.rowIndex + 1);
}
}
}