通过javascript检查活动元素是否具有特定的类

J. *_*nor 2 javascript dom

我正在编写一个单字段表单,希望Enter键将表单前进到下一个输入字段。由于页面上还有另一种形式,当该表单中的输入之一是时,我只希望按Enter键可以使该表单前进activeElement

我已经在这里完成了一个极其冗长的if()声明:

document.addEventListener( 'keydown', function( ev ) {
        var keyCode = ev.keyCode || ev.which;
        var ids = [ 'this', 'that', 'there', 'thing', 'other' ];
        if ( document.getElementById( ids[0] ) === document.activeElement || document.getElementById( ids[1] ) === document.activeElement || document.getElementById( ids[2] ) === document.activeElement || document.getElementById( ids[3] ) === document.activeElement || document.getElementById( ids[4] ) === document.activeElement) {
            if( keyCode === 13 ) {
                ev.preventDefault();
                self._nextQuestion();
            }
        }
    } );
Run Code Online (Sandbox Code Playgroud)

每个输入都属于同一类:.questions。我已经尝试过类似的东西:

document.addEventListener( 'keydown', function( ev ) {
    var keyCode = ev.keyCode || ev.which;
    var ids = [ 'this', 'that', 'there', 'thing', 'other' ];
    if ( document.querySelector('.questions') === document.activeElement) {
        if( keyCode === 13 ) {
            ev.preventDefault();
            self._nextQuestion();
        }
    }
} );
Run Code Online (Sandbox Code Playgroud)

但是,当然,这仅访问.questions页面上的第一个实例。我不想遍历节点,因为它似乎并不比我现有的要好得多。

我是新手,我正在寻找更简洁的逻辑。

Col*_*inD 5

只需检查是否activeElement具有questions课程。

var pattern = /(?:^|\s)questions(?:\s|$)/
if (document.activeElement.className.match(pattern)) {
  ...
}
Run Code Online (Sandbox Code Playgroud)

squint提供了改进的正则表达式,可以解决类名中的更多时髦情况。

  • 仅供参考:`document.activeElement.classList.contains('questions')` (2认同)