jQuery:在整个文档上触发按键功能,但不在输入和文本区域内触发按键功能吗? [英] jQuery: trigger keypress function on entire document but not inside inputs and textareas?

查看:74
本文介绍了jQuery:在整个文档上触发按键功能,但不在输入和文本区域内触发按键功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个……

$(document).keypress(function(e) {
        if ( e.keyCode === 119 ) // w
            doSomething();
    });

Wo在我的文档上按"w"时,会触发doSomething()函数.当前在input字段或textarea中键入(焦点对准)时,如何防止其触发?

Wo when pressing "w" on my document the doSomething() function fires. How can I prevent it from firing when I'm currently typing (in focus) in an input field or textarea?

推荐答案

您必须在事件之后而不是在选择器中过滤出元素,像这样

You'll have to filter out the elements after the event and not in the selector, like this

$(document).on('keypress', function(e) {
    var tag = e.target.tagName.toLowerCase();
    if ( e.which === 119 && tag != 'input' && tag != 'textarea') 
        doSomething();
});

这将检查event.target的标记名,该事件的起源元素,并且仅在事件不是起源于输入或文本区域时才触发该函数.

this checks the tagname of the event.target, the element the event originated from, and only fires the function if the event did not originate from an input or textarea.

这篇关于jQuery:在整个文档上触发按键功能,但不在输入和文本区域内触发按键功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆