javascript - 向表格行添加 onclick 事件

标签 javascript html dom dom-events

我正在尝试通过 Javascript 将 onclick 事件添加到表格行。

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”(或类似的东西)这一事实有某种关系。

如果我可以访问当前行,我可以在 onclick 函数中执行 getElementById,但我找不到这样做的方法。有什么建议吗?

最佳答案

像这样。

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

编辑

工作 demo .

关于javascript - 向表格行添加 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1207939/

相关文章:

javascript - 使用nodejs上传大文件

javascript - 事件仅在触发两次时才会触发

javascript - javascript代码在浏览器上可见

html - HTML UL LI 元素(列表元素)有多贵?

javascript - 谷歌图表 ChartWrapper 获取无效的列索引

javascript - 检查点是否位于两组坐标之间

Javascript 鼠标滚动增量

dom - 将流与 document.querySelector 一起使用

jquery - 使用 jQuery(或纯 JS)添加新的 DOM 元素

javascript - 为什么在 Canvas 中创建的行为不遵循规定的宽度和高度?