首页 > 解决方案 > 如何在javascript中读取多个值长度?

问题描述

我正在使用条形码扫描仪,目前遇到一个问题,我需要条形码来读取 2 个不同的值长度,目前我将其设置为以 9 长度提交值。

          <span>
                <input type="text" id="IC-input" name="IC" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="12">
                <label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
          </span>

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 9){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
    }

现在我也需要它从 12 个值中读取,但是当值达到 9 位时它会自动提交。我试过 OR 函数。

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 12 || value.length == 9){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
    }

我也尝试了 Else 功能

        function autofill(value){
        console.log("Autofill:"+value)
        //console.log(9 digits);
        button = document.getElementById("theButton");
        if(value.length == 12){
            console.log('form is ready to submit');
            theButtonIsPressed(value);
        } 
        else if(value.length == 9){
            theButtonIsPressed(value);
        }
    }

但它总是会读取前 9 个值,而其他 3 个值未读。有人对此有解决方案吗?先感谢您。

标签: javascripthtml

解决方案


好像你正在听按键。使用计时器取消它。去抖方法的基本思想。

var timer;
function autofill(value){
  if (timer) window.clearTimeout(timer);
  if(value.length === 9){
    timer = window.setTimeout( function () {
      processIt(value);
    }, 50);
  } else if(value.length === 12){
    processIt(value);
  } 
}

function processIt(value){
  console.log('here', value);
}

但这是一个糟糕的解决方案。通常,您将扫描仪设置为触发选项卡或输入新闻,以便您知道它已完成。我会检查是否正在发生这种情况并改为倾听。然后你可以只听它,你就知道扫描仪已经完成了。

var inp = document.getElementById("barcode");
inp.addEventListener("keydown", function (evt) {
  if (["Tab", "Enter"].includes(evt.key)) {
    evt.preventDefault();
    console.log('scanner is done', evt.target.value);
  }
});
<input type="text" id="barcode" />


推荐阅读