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).