我正在开发一个简单的条形码系统。它的作用是遍历json-string
以找到EAN代码的匹配。如果是,它将根据product
添加产品。然而。如何更改代码以查找EAN在JSON字符串中是否有效/找不到。我认为下面会解决它。但它没有。如果EAN有效,它可以工作。但是如果找不到EAN,我还需要做一些其他事情。
<script>
var barcode = "";
$(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 >= 9) {
barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
$('#barcode').myfunction(barcode);
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
var search_json = <?= $ean ?>;
(function( $ ){
var match = "NO";
$.fn.myfunction = function(barcode) {
$.each(search_json, function(i, v) {
if (v.ean == barcode) {
alert(v.qty + ’ of ' + v.product + ’ added');
match = "YES";
return;
}
});
if(match == "NO"){
alert("EAN not found");
}
return this;
};
})( jQuery );
</script>
答案 0 :(得分:0)
我建议使用简单的查找。我假设搜索json是一个像这样的对象数组。
var jsonList = [ { ean: 1 }, { ean: 2 } ];
var barcode = 1;
var match = jsonList.find(obj => obj.ean === barcode);
希望这会有所帮助。