我想实时检测条形码,我用 USB 条形码扫描仪扫描条形码以获取价格或 ISBN,我将检测文本字段的字符串长度。满足条件会触发一些函数
但是我运行了以下代码并在 Firexfox 上运行了一段时间,然后我的 CPU 使用率超过 100%(Intel i5 3570K 3.xGHZ)并且还消耗了很多内存,
有没有更好的解决方案可以让我完成任务?
谢谢你们。
<head>
<style type="text/css">
.close_ime{ime-mode:disabled;}
</style>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.js" ></script>
<script>
$(document).ready(function () {
var pressed = false;
var chars = [];
$(window).keypress(function (e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function () {
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
// assign value to some input (or do whatever you want)
$("#barcode").val(barcode);
}
chars = [];
pressed = false;
}, 500);
}
pressed = true;
});
});
$("#barcode").keypress(function (e) {
if (e.which === 13) {
console.log("Prevent form submit.");
e.preventDefault();
}
});
</script>
</head>
<body>
<input type="text" class="close_ime" id="barcode" placeholder="Waiting for barcode scan..." size="40">
</body>