如何使用JavaScript将onclick事件添加到表格单元格?

时间:2018-12-28 07:18:43

标签: javascript html

我正在使用JavaScript insertRow方法向现有表添加行 对于一个单元格,我想添加一个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>

5 个答案:

答案 0 :(得分:1)

onclick是html属性,您已为此处理程序click事件分配了一个函数。

在这种情况下:

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

答案 1 :(得分:0)

如下更新功能

   <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>

答案 2 :(得分:0)

我认为问题在于,您如何将事件附加到cell1?尝试以下代码:

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; //<-- problem was on this line
}

答案 3 :(得分:0)

使用下面的一个。

cell1.addEventListener('click', xfunc);

答案 4 :(得分:0)

首先,您可以尝试一些非常简单的事情:

cell1.setAttribute('onclick', 'xfunc()');

也许这已经解决了您的问题。 如果不是这样,您只能在单元格内使用DIV:

var div = document.createElement('div');
div.setAttribute('onclick', 'xfunc()');
div.setAttribute('style', 'height: 100%; width: 100%');
div.innerHTML = 'NEW CELL1';
cell1.appendChild(div);

这应该可以解决问题。

我不确定的唯一一件事是表单元是否具有onclick属性:)

LG

相关问题