Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
688 views
in Technique[技术] by (71.8m points)

html - Javascript onClick event in all cells

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...