JavaScript to add table row onclick events

后端 未结 3 1889
栀梦
栀梦 2021-01-15 15:06

I\'m new to Javascript. I want to add onclick events to table rows. I\'m not using JQuery.

I loop thru the rows and use a closure to make sure I have the state of th

3条回答
  •  春和景丽
    2021-01-15 15:44

    This seem to be the canonical way

    DEMO

    function example4() {
        var table = document.getElementById("tableid4");
        var rows = table.rows; // or table.getElementsByTagName("tr");
        for (var i = 0; i < rows.length; i++) {
            rows[i].onclick = (function() { // closure
                var cnt = i; // save the counter to use in the function
                return function() {
                  alert("row"+cnt+" data="+this.cells[0].innerHTML);
                }    
            })(i);
        }
    }
    window.onload = function() { example4(); }​
    

    UPDATE: @ParkerSuperstar suggested that the i in (i) is not needed. I have not tested this but his fiddle seems to work.

提交回复
热议问题