javascript - 如何在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 个值未读。有人对此有解决方案吗?先感谢您。
解决方案
好像你正在听按键。使用计时器取消它。去抖方法的基本思想。
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" />
推荐阅读
- mysql - 在 Spring Data JPA 中构建 FULLTEXT 搜索 SQL Native Query
- java - 从一个 java 类创建另一个 java 类 (POJO)
- firebase - 在firebase的嵌套集合中查询文档值
- android - 共享图像
- python - ImportError:无法从“bs4.element”导入名称“样式表”
- javascript - 如何通过 id Javascript
- javascript - 如何在表格行jQuery中创建3点下拉按钮
- javascript - 在命令处理程序中获取 API 延迟
- prometheus - Prometheus:查询以查找最后 100 个/固定请求的状态?
- java - 在 Headless (HtmlUnitDriver) 模式下执行测试,在 Eclipse IDE 上通过,但在 JMeter 中执行时失败