JavaScript to add table row onclick events
<p>I'm new to Javascript. I want to add onclick events to table rows. I'm not using JQuery.</p>

<p>I loop thru the rows and use a closure to make sure I have the state of the outer function for each row.
The looping works. Using alerts, I see the function being assigned for each iteration. But when I click the row, no alert is displayed.
Below is the HTML and code that can be loaded.</p>

<p>Why are the table row events not working?</p>

<pre><code>&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;body&gt;
&lt;script&gt;
function example4() {
    var table = document.getElementById("tableid4");
    var rows = table.getElementsByTagName("tr");
    for (var i = 0; i &lt; rows.length; i++) {
        var curRow = table.rows[i];
        //get cell data from first col of row
        var cell = curRow.getElementsByTagName("td")[0];
        curRow.onclick = function() {
            return function() {
                alert("row " + i + " data="+ cell.innerHTML);
            };
        };
    }
}
function init() { example4(); }
window.onload = init;   
&lt;/script&gt;
&lt;div&gt;
Use loop to assign onclick handler for each table row in DOM. Uses Closure.
    &lt;table id="tableid4" border=1&gt;
      &lt;tbody&gt;
        &lt;tr&gt;&lt;td&gt;Item one&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Item two&lt;/td&gt;&lt;/tr&gt;
        &lt;tr&gt;&lt;td&gt;Item three&lt;/td&gt;&lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
