Click on HTML table and get row number (with Javas

2020-05-31 12:49发布

I would like to know how to click on a button in an HTML table and get the row and column number returned to me: For example, with the following table:

<table>
  <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
    <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
    <tr>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    <td><input type="button" value="button"></td>
    </tr>
  </table>

How would I use JavaScript to click on the first button in the second row and have it tell me that I clicked on the first cell in the second row? Does each button need to have a unique id, or not?

2条回答
看我几分像从前
2楼-- · 2020-05-31 12:56

Try this:

function  getId(element) {
    alert("row" + element.parentNode.parentNode.rowIndex + 
    " - column" + element.parentNode.cellIndex);
}
<table>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
  <tr>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
    <td><input type="button" value="button" onclick="getId(this)"></td>
  </tr>
</table>

查看更多
SAY GOODBYE
3楼-- · 2020-05-31 13:09

Most generic version of @Gremash js function

function  getId(element) {
    alert("row" + element.closest('tr').rowIndex + 
    " -column" + element.closest('td').cellIndex);
}
查看更多
登录 后发表回答