按下回车键时如何移动到下一个输入字段?

How to move to next input field when enter key is pressed?

在 console.log('successful') 之后写什么,以便我使用 id 进入下一个输入字段?

 <script>
    function invokeFunc() {
        addEventListener('keydown', function(evt) {
        var whichKey = checkKey(evt);
        if (whichKey == 13) {                            
            console.log('successful');
        }
        });
    }
    function checkKey(evt) {
        console.log(evt.which);
        return evt.which;
    }
</script>

应该可行:

if (whichKey == 13) {
    console.log('successful');
    evt.preventDefault(); // if it's inside <form> tag, you don't want to submit it
    document.getElementById('nextInputID').focus();
}

如果输入字段像这样彼此相邻,我的方法将起作用

<input type="text">
<input type="text">

您可以通过弄清楚当键码为 13 时如何获取下一个输入字段来改进这一点 在我的例子中,我使用 nextelementsibling 并检查它是否是一个输入(*你可以添加或逻辑 || nextEl.nodeName === 'SELECT') 如果 nextElement 是表单字段,则 focus() 放在它上面,如果你没有完成

document.querySelectorAll('input').forEach( el => {
            console.log(el)
            el.addEventListener('keydown', e => {
                console.log(e.keyCode);
                if(e.keyCode === 13) {
                    let nextEl = el.nextElementSibling;
                    console.log(nextEl)
                    if(nextEl.nodeName === 'INPUT') {
                        nextEl.focus();
                    }else {
                        alert('done');
                    }
                }
            })
        })