【问题标题】:jQuery. Google-like autofocus?jQuery。类似谷歌的自动对焦?
【发布时间】:2012-02-11 17:32:19
【问题描述】:

当我敲击键盘上的任何字母时,我想将焦点设置到输入字段。但是……

1) … 加载 DOM 后动态添加字段

2) ... 我不知道如何只查找字母(没有数字、箭头等)

$("#table_filter").on("load", function(event){
  alert('TEST');
});

我必须在哪里告诉 jQuery 照顾按键? 对不起,我对 jQuery 很不熟悉 :(

【问题讨论】:

  • @JonH:好点,虽然 OP 确实改变了问题(我评论时没有点)。
  • @qwertymk - 这意味着您的解决方案将不起作用。一开始我误读了这个问题,但你很快就对我投了反对票,所以我删除了我的答案。
  • @JonH:我投了反对票,因为.live() 已被弃用,取而代之的是.on()
  • @qwertymk - 举个例子……你在我编辑的时候没有等到,你没有足够的代表来查看我删除的答案,但上面写着:If it is loaded after (dynamically) you need to look at live http://api.jquery.com/live/ Err live is deprecated now and says to use .on.
  • @suntrop 我“取消”删除了我的帖子 - 它应该会有所帮助。您需要在 jQuery 中查看 .on() 上的注释以解析动态控件。

标签: jquery focus keypress


【解决方案1】:

以下代码应该完全符合您的要求。我在编写代码时对其进行了注释,因此它应该很容易理解。请记住,某些键盘可能会返回不同的键输入(但不确定原因)

在我试图提供帮助的另一篇文章中,这个人一直坚持 19 = Enter,但我有几个工作程序另有说明。他声称使用的是工厂键盘,但正如我所提到的,他仍然不确定这个缺陷。据我所知,19 = 暂停/中断键(如果存在)。所以你可能想用不同的键进行测试,以确保我下面的“if”语句是正确的。

如果有帮助,我会为你准备一个 jsfiddle,它应该会显示你按下的每个键的数字。只需单击第一个输入框,然后按任意键即可在第二个框中查看其 .which 代码。 -> http://jsfiddle.net/SpYk3/KCzvh/

$(function() {
   // Create new input
   var newInp = $("<input />");
   // Place it wherever
    newInp.appendTo($("body"));
    $(document).keyup(function(e) {
        // event.which is the "keycode" of each key on keyboard
        // 65 = a, 90 = z, the other letters fall between the 2
        // 90 - 26 = 64! tada, you see all 26 letters from 65 to 90!
        if (e.which >= 65 && e.which <= 90) newInp.focus();

        // if you wanted to focus it for numbers too ...
        // numbers on qwerty side of key board are 48 - 57
        if (e.which >= 48 && e.which <= 57) newInp.focus();
        // numbers on num lock side tend to be 96 - 105
        if (e.which >= 96 && e.which <= 105) newInp.focus();
    });
});

【讨论】:

    【解决方案2】:

    如果它是在(动态)之后加载的,你需要查看live

    http://api.jquery.com/live/

    Err live 现已弃用,并表示要使用 .on

    这将涵盖 DOM 的第 1 点。对于第 2 部分,您可以使用 jquery numberic 之类的插件:http://www.texotela.co.uk/code/jquery/numeric/ - 或构建与此类似的东西:http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values

    【讨论】:

    • @qwertymk:我把它拿回去然后一些
    猜你喜欢
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 2012-05-22
    相关资源
    最近更新 更多