jQuery委托方法不适用于keydown和keypress [英] jQuery delegate method not working for keydown and keypress

查看:68
本文介绍了jQuery委托方法不适用于keydown和keypress的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得TAB键

如果按下,那么

执行我的代码

和e.preventDefault();

I want to get TAB key
If pressed then
execute my code
and e.preventDefault();

$().ready(function(){
   $("div").delegate(".note","keydown",function(e){
        //not working
    });

   $("div").delegate(".note","keypress",function(e){
        //not working
    });

   $("div").delegate(".note","click",function(e){
        //working fine
    });
});

进行测试我只用alert(9)检查了上述事件;

只有在keypress和keydown不起作用的时候才能点击事件。

for testing I have checked the above events with only alert(9);
only click event works while keypress and keydown doesn't work.

推荐答案

实际上, keydown keypress 的目标为 body ,除非元素处于焦点状态:

Actually, keydown and keypress have the target of body unless an element is in focus:


当一个元素关注时,文档接收到的关键事件必须以
为目标在该元素处。可能没有重点;当没有关注
元素时,文档接收到的关键事件必须是以body元素为准的

When an element is focused, key events received by the document must be targeted at that element. There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element.

来源: https://www.w3。 org / TR / html50 / editing.html#焦点

所以这个问题不是委托自己,而是让一个元素可以聚焦(你的处理程序只是不火!)。对于能够接收焦点的任意元素,对于应该具有按键事件处理程序的元素使用 tabindex 属性(详细了解 here )。

So the problem is not delegating itself but rather making an element focusable (your handlers just don't fire!). For an arbitrary element to be able to recieve focus, use the tabindex attribute for the elements that are supposed to have key event handlers (learn more here).

这篇关于jQuery委托方法不适用于keydown和keypress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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