向表格行添加 onclick 事件 [英] Adding an onclick event to a table row

查看:34
本文介绍了向表格行添加 onclick 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Javascript 向表格行添加 onclick 事件.

I'm trying to add an onclick event to a table row through Javascript.

function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 1; i < rows.length; i++) {
        row = table.rows[i];
        row.onclick = function(){
                          var cell = this.getElementsByTagName("td")[0];
                          var id = cell.innerHTML;
                          alert("id:" + id);
                      };
    }
}

这在 Firefox 中按预期工作,但在 Internet Explorer (IE8) 中我无法访问表格单元格.我相信这与 onclick 函数中的this"被标识为Window"而不是Table"(或类似的东西)有某种关系.

This works as expected in Firefox, but in Internet Explorer (IE8) I can't access the table cells. I believe that is somehow related to the fact that "this" in the onclick function is identified as "Window" instead of "Table" (or something like that).

如果我可以访问当前行,我可以在 onclick 函数中执行 getElementById ,因为我找不到方法来做到这一点.有什么建议吗?

If I could access the the current row I could perform a getElementById in the onclick function by I can't find a way to do that. Any suggestions?

推荐答案

类似这样的事情.

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

编辑

工作 演示.

这篇关于向表格行添加 onclick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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