将onclick事件添加到表行

26 html javascript 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);
                      };
    }
}
Run Code Online (Sandbox Code Playgroud)

这在Firefox中可以正常工作,但在Internet Explorer(IE8)中,我无法访问表格单元格.我认为这在某种程度上与onclick函数中的"this"被识别为"Window"而不是"Table"(或类似的东西)这一事实有关.

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

谢谢!

Sol*_*ogi 37

像这样的东西.

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑

工作演示.


Nic*_*ggs 7

我认为对于 IE,您将需要使用Event 对象的 srcElement 属性。如果 jQuery 是您的一个选择,您可能需要考虑使用它 - 因为它为您抽象了大多数浏览器差异。示例jQuery:

$("#tableId tr").click(function() {
   alert($(this).children("td").html());
});
Run Code Online (Sandbox Code Playgroud)


Zol*_*ari 6

简单的方法是生成如下代码:

<!DOCTYPE html>
<html>
<head>

<style>
  table, td {
      border:1px solid black;
  }
</style>

</head>
<body>
<p>Click on each tr element to alert its index position in the table:</p>
<table>
  <tr onclick="myFunction(this)">
    <td>Click to show rowIndex</td>
  </tr>
  <tr onclick="myFunction(this)">
    <td>Click to show rowIndex</td>
  </tr>
  <tr onclick="myFunction(this)">
    <td>Click to show rowIndex</td>
  </tr>
</table>

<script>
  function myFunction(x) {
      alert("Row index is: " + x.rowIndex);
  }
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)