如何检测单击哪一行[tr]? [英] How to detect which row [ tr ] is clicked?

查看:104
本文介绍了如何检测单击哪一行[tr]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中,我们如何检测单击哪一行表?目前我正在做的是,我在运行时绑定该方法,就像这样。

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

[复制自[ 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.


  • 请不要jQuery:D。

推荐答案

您可以使用 事件委派 。基本上你在表中添加一个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;
   };

这篇关于如何检测单击哪一行[tr]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆