【问题标题】:Access nextSibling when some inputs are inside parent elements当某些输入在父元素内时访问 nextSibling
【发布时间】:2021-02-17 13:08:08
【问题描述】:
我有一个 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>
感谢您的帮助!
【问题讨论】:
标签:
javascript
focus
nextsibling
【解决方案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>