简体   繁体   English

Jquery .not() 等效于 javascript

[英]Jquery .not() equivalent in javascript

I want to implement a shortcut feature using a simple keystroke although I don't want to trigger the shortcuts when the user types in an input or a textarea.我想使用简单的按键来实现快捷方式功能,尽管我不想在用户输入输入或文本区域时触发快捷方式。

I noticed that Jquery has a .not() method which allows this:我注意到 Jquery 有一个 .not() 方法,它允许这样做:

$(document).not("input").on('keyup keydown keypress', function(event) {
    console.log(event);
    if(event.key == 'n') {
        alert('n pressed outside of input');
    }
});

Therefore I am looking for an equivalent in plain javascript or a function that would check if the user isn't focusing an input.因此,我正在寻找一个等价的纯 javascript 或一个函数来检查用户是否没有关注输入。

document.onkeypress = (event) => {
    if (event.key == 'n') {
        console.log('n has been pressed! (input or not)');
    }
};

Answer has been posted by @ChrisG in the comments 答案已由@ChrisG发表在评论中

Although it is NOT a .not() substitute it solved my problem 尽管它不是.not()替代品,但它解决了我的问题

Indeed, event.target.tagName returns the name of the tag in uppercase for my part. 确实, event.target.tagName返回大写标签的名称。

Therefore this code works: 因此,此代码有效:

document.onkeypress = (event) => {
    if (event.key == 'n' && event.target.tagName != 'INPUT' && event.target.tagName != 
    'TEXTAREA') {
        addTodo.click();
    }
};

Your answer is correct, but for your question: Jquery .not("input") equivalent in javascript is document.querySelectorAll(":not(input)"). 您的答案是正确的,但是对于您的问题:javascript中的Jquery .not(“ input”)等效项是document.querySelectorAll(“:not(input)”)。

It returns an array of elements except input elements 它返回输入元素以外的元素数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM