在onkeypress上获取表的Row索引

时间:2017-04-28 12:33:21

标签: javascript jquery html

如何在keypress上获取表的行索引

<table>
  <tr>
    <td><input type="text" onkeypress="test(this)"/></td>
  </tr>
  <tr onclick="test2(this)">
    <td>Click to show rowIndex</td>
  </tr>
  <tr onclick="test2(this)">
    <td>Click to show rowIndex</td>
  </tr>
</table>

<script>
function test(x)
{
 alert("Row index is: " + x.rowIndex);
}
function test2(x) {
    alert("Row index is: " + x.rowIndex);
}
</script>

我很困惑,因为test2返回行,但测试一显示未定义。 任何解释为什么它返回undefined以及获取索引的正确方法都将非常感激。

3 个答案:

答案 0 :(得分:2)

您应该为数组中的元素指定一个类名,以便在需要获取它们时更容易找到它们。我们假设您为单元格table-cell和行table-row命名:

$('#Items').on('click', '.table-cell', function(){
      $(this); // the clicked cell
      $(this).parent('.table-row); // the row in which the clicked cell is
});

答案 1 :(得分:2)

localStorage

输入的父级是td,而td的父级是tr。将onkeypress绑定到input元素。并点击tr元素

答案 2 :(得分:0)

文本框的事件为onkeypress,因此当您传递this时,脚本会收到[HTMLInputElement]类型的对象,而当您调用事件时单击test2 {{1} } javascript收到x为onclick

因此文本框中没有[HTMLTableRowElement]属性可用,对于脚本,它仍未定义。

相关问题