且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测单击哪一行[tr]?

更新时间:2023-02-13 20:27:27

您可以使用 事件委派 。基本上你在表中添加一个clickhandler。此处理程序读出所单击元素的标记名,并向上移动DOM树,直到找到包含的行。如果找到一行,它会对其起作用并返回。类似的东西(尚未测试,但可能会给你一些想法):

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