首页 > 解决方案 > 如何使用 javascript 将 onclick 事件添加到表格单元格?

问题描述

我正在使用 JavaScriptinsertRow方法向现有表中添加行 对于一个单元格,我想添加一个onclick事件。

我怎样才能使用纯 JavaScript 做到这一点?

我附上我的代码。

<!DOCTYPE html>
<html>
    <head>
        <style>
        table, td {
          border: 1px solid black;
        }
        </style>
    </head>
    <body>    
        <table id="myTable">
          <tr>
            <td>Row1 cell1</td>
            <td>Row1 cell2</td>
          </tr>

        </table>
        <br>
        <button onclick="myFunction()">Try it</button>
        <script>
        function myFunction() {
          var table = document.getElementById("myTable");
          var row = table.insertRow(0);
          var cell1 = row.insertCell(0);
          var cell2 = row.insertCell(1);
          cell1.innerHTML = "NEW CELL1";
          cell2.innerHTML = "NEW CELL2";
          cell1.onclick()="xfunc()";
        }

        function xfunc(){
        alert("Hi")
        }
        </script>
  </body>
</html>

标签: javascripthtml

解决方案


onclick是一个 html 属性,你已经为这个属性分配了一个函数来处理点击事件。

在你的情况下:

cell1.onclick = xfunc; // instead of cell1.onclick()="xfunc()";

推荐阅读