Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In javascript, how can we detect which row of the table is clicked? At present what i am doing is, i am binding the the method at run time like this.

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);
        }
    }
}

[ copied from [ http://webdesign.maratz.com/lab/row_index/ ] ]

But i don't like this approach. Is there any alternative? My problem is just to get the index of the row which is clicked.

  • No jQuery please :D.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
454 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use event delegation for that. Basically you add one clickhandler to your table. This handler reads out the tagname of the clicked element and moves up the DOM tree until the containing row is found. If a row is found, it acts on it and returns. Something like (not tested yet, but may give you ideas):

    var table = document.getElementById('my_table');
    table.onclick = function(e) {
       e = e || event;
       var eventEl = e.srcElement || e.target, 
           parent = eventEl.parentNode,
           isRow = function(el) {
                     return el.tagName.match(/tr/i));
                   };

       //move up the DOM until tr is reached
       while (parent = parent.parentNode) {
           if (isRow(parent)) {
             //row found, do something with it and return, e.g.
              alert(parent.rowIndex + 1); 
              return true;
           }
       }
       return false;
   };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...