jQuery:从键盘听自动扫描仪输入? [英] jQuery: Listening for automated scanner input from keyboard?

查看:94
本文介绍了jQuery:从键盘听自动扫描仪输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为附有条形码扫描仪的图书馆系统编写一个Web应用程序。扫描仪的输入显示为键盘输入,它始终为 ~~ [\d] +。[\ d] + ~~ 形式,例如 ~~ 470.002 ~~

I'm writing a web app for a library system with a barcode scanner attached. The scanner's input presents as keyboard input, and it's always of the form ~~[\d]+.[\d]+~~, for example ~~470.002~~.

我想为扫描仪输入设置一个jQuery监听器,我是一个jQuery新手。它应该监听所有键盘输入,但只有在听到扫描仪输入时才会执行操作,并且仅在扫描仪输入完成时执行。

I want to set up a jQuery listener for scanner input, and am a jQuery novice. It should listen to all keyboard input, but only perform an action when it hears input from the scanner, and only when the scanner input has finished.

这是至于我有(即不是很):

This is as far as I've got (i.e. not very):

//Global functions: call on all pages.
$(document).ready(function() {
    // Listen for scanner input. 
    $(window).keypress(function(e) {
        var key = e.which;
        if (key==126) {.
            alert('tilde');
            // How to listen for the correct input?
            // check_out_book();
        }
    });
});

以我需要的格式保持收听输入的最佳方法是什么?在调用 check_out_book()之前,我希望能听到最后两个代码。

What's the best way to keep listening input in the format I need? I'd like it to listen for the final two tildes before calling check_out_book().

如果有暂停的话,我还希望在第一个代字号后停止聆听 - 区分人类打字员和自动扫描仪输入。 jQuery有办法做到这一点吗?

I'd also like it to 'stop' listening after the first tilde if there is a pause - to distinguish between a human typist and the automated scanner input. Does jQuery have a way to do this?

任何指针都非常感谢!谢谢。

Any pointers very much appreciated! Thank you.

推荐答案

我想你想通过存储到目前为止收到的内容并检查它是否有效来做到这一点。如果不是,请丢弃您收到的内容并重新开始:

I think you want to do this by storing what you've received so far and checking to see if it's valid. If it is not, discard what you have received and start again:

$(document).ready(function(){
    var input = '',
        r1 = /^~{1,2}$/,
        r2 = /^~{2}\d+$/,
        r3 = /^~{2}\d+\.$/,
        r4 = /^~{2}\d+\.\d+$/,
        r5 = /^~{2}\d+\.\d+~{1}$/
        r6 = /^~{2}\d+\.\d+~{2}$/;

    $(window).keypress(function(e) {
        input += String.fromCharCode(e.which);

        if (r1.test(input) || r2.test(input) || r3.test(input) || r4.test(input) || r5.test(input)) {
            // input is valid so far, continue
        } else if (r6.test(input) {
            // input is valid and complete
            check_out_book();
        } else {
            // input is invalid, start over
            input = '';
        }
    });
});

你可以结合一个将那些正则表达式分成两部分,但我认为这样更清晰。

You could combine all those regexps into two, but I think it's more legible this way.

这篇关于jQuery:从键盘听自动扫描仪输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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