jQuery keypress() - 获取所有字符,直到输入被按下

时间:2015-04-03 13:05:30

标签: javascript jquery keypress keyup

我正在尝试创建一个从文档中读取的按键/键盘功能(而不是从输入字段中读取) - 我将把它用于条形码扫描设备。

功能

    $(document).keyup(function(e) {
      var barcode = e.which;
      // the barcode should be without the enter at the end

      if (e.keyCode == 13){
         // stop reading 
      }
    });

我对javascript和jQuery很新 - 你可能已经注意到了。

感谢您的帮助!

更新

这对我有用:

    $(function(){

            var barcode = '';

            var getCode = function (e) {
                if (e.which != 13) {
                    barcode += String.fromCharCode(e.which);
                } else {
                    $(document).unbind('keyup', getCode);
                    console.log(barcode);
                }
            };

            $(document).on('keypress', getCode);

            // Barcode ausgeben


            // Produktinfos ausgeben
            $('span#articleID').text('articleID');
            $('span#productName').text('productName');

        });

谢谢大家!!

4 个答案:

答案 0 :(得分:1)

创建一个在keyup上绑定的函数。当按下Enter键时,只需取消绑定该功能以确保代码不再发生变化。

var barcode = '';

var getCode = function (e) {
    if (e.which != 13) {
        barcode += e.which;
    } else {
        $(document).unbind('keyup', getCode);
        console.log(barcode);
    }
};

$(document).on('keyup', getCode);

答案 1 :(得分:0)

你在找这个吗?



$(document).keyup(function (e) {
    
     if (e.keyCode == 13) {
         console.log("Stopped");
         e.preventDefault();
         return false;
     } else {
        var barcode = e.which;
     // the barcode should be without the enter at the end
         $("#dvStatus").append("</br> " + e.key + " Key should be logged");
     }
 });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dvStatus">
  </div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

也许是这样的:

var BarCodeStr='';

document.onkeydown=function(e){

if (e.keyCode===13) {ProcessBarCodeStr(); BarCodeStr='';} else {BarCodeStr=BarCodeStr+e.keyCode;}

}

答案 3 :(得分:0)

您可以考虑删除换行符(\ n)。在这种情况下,您正在寻找:

$(document).keyup(function(e) {
  //check for different types of newlines
  var barcode = e.which.replace(/(\r\n|\n|\r)/gm,"");

  if (e.keyCode == 13){
     // stop reading 
  }
});