JavaScript to add table row onclick events

后端 未结 3 1875
栀梦
栀梦 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:43

    I'm not quite sure why you're using a closure here, could you be a bit more elaborate?

    The reason you're not seeing the desired alert is because within the onclick function, you're returning another function. I.e:

    window.onload = function() {
        return function() {
            alert("Closure... why?");
        };
    };
    

    Something like this won't really work because you're never calling the nested function... try it without using the closure, or comment explaining why you want a closure because you're explanation didn't make much sense to me.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-15 15:52

    You just have to remove an extra function and script will be like this

    <script>
     function example4() {
        var table = document.getElementById("tableid4");
    cells = table.getElementsByTagName('td');
    
     for (var i=0,len=cells.length; i<len; i++){
     cells[i].onclick = function(){
        alert(this.innerHTML);
    
    }
     }
    }
     function init() { example4(); }
     window.onload = init;   
     </script>
    
    0 讨论(0)
提交回复
热议问题