1

我有一个 html 表,其中一些<input>在一些<td>. 当当前输入的值不同于"". 但是,这不起作用,因为输入元素不直接相互跟随

let cells = document.querySelectorAll('td > input');

for (let x of cells) {
  x.maxLength = 1;
  x.type = 'text';
  x.onkeyup = function() {
    if (this.value != '') { this.nextSibling.focus() } //HERE
  }
}
<table>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
</table>

感谢帮助!

4

1 回答 1

1

您可以只获取index当前单元格的 并使用它而不是nextSibling.

let cells = document.querySelectorAll('td > input');

for (let x of cells) {
  const index = [...cells].indexOf(x); // Get index of current cell
  
  x.maxLength = 1;
  x.type = 'text';
  x.onkeyup = function() {
    if (this.value != '' && cells[index + 1]) { // Check if the next cell exists
      cells[index + 1].focus(); // Focus next cell
    }
  }
}
<table>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
  <tr>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
    <td> <input> </td>
  </tr>
</table>

于 2021-02-17T13:17:31.963 回答