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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29042140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:46:51  来源:igfitidea点击:

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

javascripthtmlhtml-tablerow

提问by scatterbrain29

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:

我想知道如何单击 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>

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?

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

回答by Gremash

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>

回答by Tu4n3r

Most generic version of @Gremash js function

@Gremash js 函数的最通用版本

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