jQuery:TAB键的附加键? [英] jQuery: keyup for TAB-key?

查看:65
本文介绍了jQuery:TAB键的附加键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果按下Tab键,则我的脚本无法运行.快速浏览后,Tab的字符代码为9.此外,在我们交谈时,有没有更好的方法来检查是否在不使用字符代码的情况下按下了键?我问是因为使用charcode时,萤火虫不断发出以下警告:

So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

不应该使用keyup事件的'charCode'属性.该值没有意义.

The 'charCode' property of a keyup event should not be used. The value is meaningless.

无论如何,它仍然有效,所以这不是问题.这是我使用的代码:

Anyway, it still works, so that's not the problem. This is the code i use:

$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});

使用上述代码,控制台为空,不添加任何内容(使用Firebug).当然,我已经尝试实际做一些事情而不是记录文本,但是什么也没执行.那么,谁能看到为什么这行不通?有没有更好的方法来检查是否按下了键?

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

谢谢.

推荐答案

我的直觉是,当您按下Tab键时,在进行键入之前,表单的输入会失去焦点.尝试更改与主体的绑定,如下所示:

My hunch is that when you press the tab key, your form's input loses focus, before the keyup happens. Try changing the binding to the body, like this:

 $('body').keyup(function(e) {
    console.log('keyup called');
    var code = e.keyCode || e.which;
    if (code == '9') {
    alert('Tab pressed');
    }
 });

然后,如果可行(对我有用),请尝试将绑定更改为keyDown,然后返回false.这样,您就可以实现自己的自定义行为.

Then, if that works (it does for me) try changing the binding to keyDown, instead, and return false. That way you can implement your own custom behavior.

$('.yourSelector').keydown(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     alert('Tab pressed');

   return false;
   }

});

这两个中的一个应该起作用...如果它是主体,则可以在主体上附加一个keydown处理程序,然后如果是选项卡,则找到具有焦点的字段(我认为这里有函数.hasFocus()?),如果它是您想要的那个,继续并返回false.否则,让浏览器执行其操作.

One of these two should work... if it's body, you could attach a keydown handler on body, then if it's tab, find the field with focus (I think there's function .hasFocus()?), and if it's the one you want, proceed and return false. Otherwise, let the browser do its thing.

如果您想使用制表符更新字段,请在回调中尝试以下操作:

If you wanted to update the field WITH a tab character, try this in your callback:

var theVal = $(this).val();
theVal = theVal + ' ';
$(this).val(theVal);

尚未测试过,但应该可以.如果给您带来麻烦,您也可以附加3或4个空格而不是制表符.

Haven't tested it, but it should work. You could also append 3 or 4 spaces instead of the tab character, if it's giving you trouble.

这篇关于jQuery:TAB键的附加键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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