-5

我找到了一个获取被点击行数的代码,但我无法理解。

谁能解释下面的代码?

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

网址是: http ://webdesign.maratz.com/lab/row_index/

4

1 回答 1

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);
        }
    }
}
于 2013-08-11T21:42:24.187 回答