Html 所有单元格中的 Javascript onClick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19155189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:03:58  来源:igfitidea点击:

Javascript onClick event in all cells

javascripthtml

提问by Sanderr

I'm learning JavaScript and I've not that much experience. But I'm making a HTML table and I want to add in every table cell (<td>) a onClick event.

我正在学习 JavaScript,但我没有那么多经验。但是我正在制作一个 HTML 表格,我想在每个表格单元格 ( <td>) 中添加一个 onClick 事件。

<table id="1">
    <tr>
        <td onClick="tes()">1</td><td onClick="tes()">2</td>
    </tr>
    <tr>
        <td onClick="tes()">3</td><td onClick="tes()">4</td>
    </tr>
</table>

Is there another way to do this event in every cell?

是否有另一种方法可以在每个单元格中执行此事件?

采纳答案by k102

There are two ways:

有两种方式:

var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
   cells[i].onclick = function(){tes();};
}

and the other way using jQuery:

另一种使用jQuery的方式:

$('td').click(function(){tes();});

upd:

更新:

To get exactly what is needed, firstly the table must be selected, so, for the first option:

要准确获得所需内容,首先必须选择表格,因此,对于第一个选项:

var table = document.getElementById('1');
var cells = table.getElementsByTagName("td"); 
...

and for the second, the jQ selector should be like this:

对于第二个,jQ 选择器应该是这样的:

$('#1 td')

回答by Zack Niwa

I know this is a bit old, but you should use a click envent on the table and use the target value to get the cell. Instead of having a 10 x 10 table = 100 event you will have only 1.

我知道这有点旧,但是您应该在表格上使用单击环境并使用目标值来获取单元格。您将只有 1 个,而不是 10 x 10 表 = 100 个事件。

The best thing with that method is when you add new cells you don't need to bind an event again.

该方法的最佳之处在于,当您添加新单元格时,您无需再次绑定事件。

$(document).ready( function() {
    $('#myTable').click( function(event) {
      var target = $(event.target);
      $td = target.closest('td');
      
      $td.html(parseInt($td.html())+1);
      var col   = $td.index();
      var row   = $td.closest('tr').index();

      $('#debug').prepend('<div class="debugLine">Cell at position (' + [col,row].join(',') + ') clicked!</div>' );
      
    });
  });
td {
  background-color: #555555;
  color: #FFF;
  font-weight: bold;
  padding: 10px;
  cursor: pointer;
  }

#debug {
    background-color: #CCC;
    margin-top: 10px;
    padding: 10px;
  }

#debug .debugLine {
    margin: 2px 0;
    padding: 1px 5px;
    background-color: #EEE;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
</table>

<div id="debug"></div>

回答by The Alpha

You may try this too (using event delegation)

你也可以试试这个(使用事件委托)

window.onload = function(){
    document.getElementById('tbl1').onclick = function(e){
        var e = e || window.event;
        var target = e.target || e.srcElement;
        if(target.tagName.toLowerCase() ==  "td") {
            alert(target.innerHTML);
        }
    };
};

EXAMPLE.

例子。

Using jQuery

使用jQuery

$(function(){
    $('#tbl1').on('click', 'td', function(){
        alert($(this).html());
    });
});

EXAMPLE.

例子。

回答by loxxy

Try :

尝试 :

var tds = document.getElementsByTagName("td");

for(var i in tds) tds[i].onclick = tes;

and a Demo...

和一个演示...



Replace documentwith any other dom element that you need to find td's in.

文档替换为您需要在其中查找 td 的任何其他 dom 元素。

回答by willy wonka

Just the following code will return the contained text of the clicked element. In this case the td

仅以下代码将返回所单击元素的包含文本。在这种情况下,td

event.target.innerText

Example:

例子:

td
{
   border: 1px solid red;
}
     <table onclick="alert(event.target.innerText)">
        <tr>
            <td>cell 1</td>
            <td>cell 2</td>
        </tr>
        <tr>
            <td>cell 3</td>
            <td>cell 4</td>
        </tr>
    </table>

Of course you can implement it into a js and attach it to the onclick event as usual. If needed you can separate the table into thead, tbody tfoot and add the onclick event to the tbody only. In this way the event will be triggered only if the user clicks on this section of the table and not when he clicks on other elements...

当然,你可以将它实现到一个 js 中,并像往常一样将其附加到 onclick 事件。如果需要,您可以将表格分成thead、tbody tfoot 和仅将onclick 事件添加到tbody 中。这样,只有当用户点击表格的这一部分时才会触发事件,而不是在他点击其他元素时...

回答by RBT

You might not require putting onclickevent on every TDelement in your table. Providing onclickevent at the table level can do the trick easily as shown in the below code snippet:

您可能不需要在表中的onclick每个TD元素上放置事件。onclick在表级别提供事件可以很容易地做到这一点,如下面的代码片段所示:

function tes(event) {
  if (event.target.nodeName == "TD") {
    alert('TD got clicked');
  }
}
  
  td {
    border: 1px solid black;
  }
  
<html>
  <head>
    <title>Tic-Tac-Toe</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <table id='gameBoard' width="300" height="300" onclick="tes(event);">
        <tr>
          <td data-index = "0 0"></td>
          <td data-index = "0 1"></td>
          <td data-index = "0 2"></td>
        </tr>
        <tr>
            <td data-index = "1 0"></td>
            <td data-index = "1 1"></td>
            <td data-index = "1 2"></td>
        </tr>
        <tr>
            <td data-index = "2 0"></td>
            <td data-index = "2 1"></td>
            <td data-index = "2 2"></td>
        </tr>
      </table>
    </div>
  </body>
</html>

You can do the appropriate handling inside tesfunction with the help of eventparameter.

您可以在参数tes的帮助下在函数内部进行适当的处​​理event

回答by Rami

You can do something like that:

你可以这样做:

  var tbl = document.getElementById("1");
    var numRows = tbl.rows.length;

    for (var i = 1; i < numRows; i++) {
        var ID = tbl.rows[i].id;
        var cells = tbl.rows[i].getElementsByTagName('td');
        for (var ic=0,it=cells.length;ic<it;ic++) {
            cells[ic].OnClick = new function() {tes()};
        }
    }

回答by Johan

if you have access to jquery, do this

如果您有权访问 jquery,请执行此操作

$('#1 td').click(function(){

});