单击HTML表并获取行号(使用Javascript,而不是jQuery)

sca*_*n29 19 html javascript row html-table

我想知道如何单击HTML表中的按钮并获取返回给我的行和列号:例如,使用下表:

<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>
Run Code Online (Sandbox Code Playgroud)

我如何使用JavaScript点击第二行中的第一个按钮并让它告诉我,我点击了第二行中的第一个单元格?每个按钮是否需要具有唯一ID?

Gre*_*ash 37

试试这个:

function  getId(element) {
    alert("row" + element.parentNode.parentNode.rowIndex + 
    " - column" + element.parentNode.cellIndex);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 我尝试"element.parentNode.parentNode.rowIndex",但它返回undefined (3认同)

Tu4*_*n3r 7

@Gremash js函数的最通用版本

function  getId(element) {
    alert("row" + element.closest('tr').rowIndex + 
    " -column" + element.closest('td').cellIndex);
}
Run Code Online (Sandbox Code Playgroud)