Javascript onClick event in all cells

前端 未结 8 2334
忘了有多久
忘了有多久 2020-12-20 17:09

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 () a onClick event.

8条回答
  •  眼角桃花
    2020-12-20 17:30

    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.

    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('
    Cell at position (' + [col,row].join(',') + ') clicked!
    ' ); }); });
    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;
      }
    
    
    0 0 0 0 0 0
    0 0 0 0 0 0
    0 0 0 0 0 0

提交回复
热议问题