对于每个,如果没有找到提醒

时间:2017-02-05 22:30:04

标签: javascript jquery

我正在开发一个简单的条形码系统。它的作用是遍历json-string以找到EAN代码的匹配。如果是,它将根据product添加产品。然而。如何更改代码以查找EAN在JSON字符串中是否有效/找不到。我认为下面会解决它。但它没有。如果EAN有效,它可以工作。但是如果找不到EAN,我还需要做一些其他事情。

编辑(完整的JS)

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

1 个答案:

答案 0 :(得分:0)

我建议使用简单的查找。我假设搜索json是一个像这样的对象数组。

var jsonList = [ { ean: 1 }, { ean: 2 } ];
var barcode = 1;
var match = jsonList.find(obj => obj.ean === barcode);

希望这会有所帮助。