【问题标题】:How to add click event to table cell in this code?如何在此代码中将点击事件添加到表格单元格?
【发布时间】:2017-06-02 13:44:05
【问题描述】:

在这段代码中,我想用 javascript 使表格单元格可点击。

还请告诉我如何在点击事件中使用 i,j 值。

<!DOCTYPE html>
<html>
<head>
<style>
 td 
 {
   height : 30px;
   width : 30px;
   cursor: pointer;
 }
</style>

<script>
function clickHere(){
var table = document.getElementById("myTable");
var row ;
var cell;
for(var i=0;i<2;i++){
  row = table.insertRow(i);
  for(var j=0;j<2;j++){
    cell = row.insertCell(j);
  }
 }
}
</script>
</head>

<body onload="clickHere()">
 <table id = "myTable" border="1"></table>
</body>
</html>

【问题讨论】:

标签: javascript


【解决方案1】:

添加此代码:

cell.addEventListener("click",function(){
    alert("cell clicked");
});

在这段代码之后:

cell = row.insertCell(j);

它将为每个单元格添加事件监听器。点击后会显示警报。

【讨论】:

    【解决方案2】:
    var table = document.getElementById("myTable");
    
    table.addEventListener("click", function(e) {
      if (e.target && e.target.nodeName == "TD") {
        alert('Cell clicked')
      }
    });
    

    【讨论】:

    • 这对我来说是完美的开始,但不幸的是它不起作用。括号未正确闭合。这需要整理。应删除倒数第二个大括号。谢谢
    【解决方案3】:

    将单元格添加到 DOM 后,您可以向其添加 eventListeners。 所以你唯一需要做的就是添加 eventListener :)

    // here you add the cell and have a reference to it
    cell = row.insertCell(j);
    
    // now you can add eventlisteners to it
    cell.addEventListener('click', function(){
        console.log('cell clicked');
    });
    

    关于添加事件监听器:MDN

    演示:https://jsfiddle.net/kt9g8h4w/1/

    【讨论】:

      【解决方案4】:

      先添加一个点击监听,然后编写一个同名监听的函数,点击后执行。试试下面的代码:

      <!DOCTYPE html>
      <html>
      <head>
      <style>
      
      td {
      height : 30px;
      width : 30px;
      cursor: pointer;
      }
      
      
      </style>
      <script>
      
      function clickHere(){
      
      var table = document.getElementById("myTable");
      var row ;
      var cell;
          for(var i=0;i<2;i++){
            row = table.insertRow(i);
            row.addEventListener('click', clickHandlerRow);
            for(var j=0;j<2;j++){
                  cell = row.insertCell(j);
                  cell.addEventListener('click', clickHandlerColumn);
              }
          }
      }
      
      function clickHandlerRow(e) {
          alert("row clicked");
      }
      
      function clickHandlerColumn(e) {
          alert("column clicked");
      }
      </script>
      </head>
      <body onload="clickHere()">
      
      <table id = "myTable" border="1"></table>
      
      </body>
      </html>
      

      【讨论】:

        【解决方案5】:

        $("#myInput").val($(This).children().eq(0).text()); - 上面的代码 (1) 'myInput' 是我们显示所选表格单元格值的输入框的 ID。 (2)'eq(0)'->表示,输入框中需要显示的单元格位置值。

        【讨论】:

        • 您可能可以通过使用降价格式选项来提高答案的清晰度。使用tour 了解更多关于 StackOverflow 上的操作。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-15
        相关资源
        最近更新 更多