【问题标题】:jQuery keypress() - get all chars until enter is pressedjQuery keypress() - 获取所有字符,直到按下输入
【发布时间】:2015-04-03 13:05:30
【问题描述】:

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

功能

    $(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');

        });

谢谢大家!!

【问题讨论】:

  • 那有什么问题?
  • 我不知道如何停止该功能并以变量“barcode”结束,它只是条形码 - 没有输入。它也应该是 unicode。

标签: javascript jquery keypress keyup


【解决方案1】:

创建一个函数来绑定keyup。按下回车后,只需解绑该函数以确保代码不再更改。

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

【讨论】:

    【解决方案2】:

    你在找这个吗?

    $(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");
         }
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="dvStatus">
      </div>

    【讨论】:

      【解决方案3】:

      可能是这样的:

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

      【讨论】:

        【解决方案4】:

        您可以考虑改为删除换行符 (\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 
          }
        });
        

        【讨论】:

          猜你喜欢
          • 2012-01-25
          • 2015-07-13
          • 1970-01-01
          • 2016-03-13
          • 2011-03-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多