Click on HTML table and get row number (with Javascript, not jQuery)

前端 未结 2 1496
醉话见心
醉话见心 2021-02-05 06:40

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:



        
相关标签:
2条回答
  • 2021-02-05 07:02

    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>

    0 讨论(0)
  • 2021-02-05 07:24

    Most generic version of @Gremash js function

    function  getId(element) {
        alert("row" + element.closest('tr').rowIndex + 
        " -column" + element.closest('td').cellIndex);
    }
    
    0 讨论(0)
提交回复
热议问题