简体   繁体   English

使用jquery将输入值与数组值进行比较

[英]Comparing an input value to an array value using jquery

I'm using an ajax call to get a JSON file using jQuery. 我正在使用ajax调用来获取使用jQuery的JSON文件。 While I am successful in doing so and can reach the values of the file, the next challenge is to get a value of the object array and compare it to an input source. 虽然我这样做并且可以达到文件的值,但下一个挑战是获取对象数组的值并将其与输入源进行比较。 If true then print it out in a span or div... 如果为真,那么将其打印成跨度或div ...

Here is the script using jQuery: 这是使用jQuery的脚本:

<!doctype html>
<html>
<head>
    <title>jQuery.getJSON demo</title>
</head>

<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    /*
    $.getJSON('zipcodes.json', function(data){
        console.log('It worked!');
    //test
}); 
    */

    $.ajax({
    url: 'zipcodes.json',
    dataType: 'json',
    type: 'get',
    cache: false,
    success: function (data) {
        $(data.zipcodes).each(function(index, value) {

            console.log(value.zip);

        });
    }

});
</script>

the JSON file is: JSON文件是:

{
    "zipcodes": [
    {
        "zip": "20002",
        "city": "Washington",
        "state": "DC"
      },
      {
        "zip": "10001",
        "city": "New York",
        "state": "NY"
      }
  ]
}

The JSON file is valid but I guess I'm trying to figure out a comparison in values of zip eg JSON文件是有效的,但我想我正在尝试找出zip值的比较,例如

if a var text = '10001' == value.zip within the array return the city and state within the HTML I can implement that part but in the jQuery portion I do not know how to get an index. 如果数组中的var text ='10001'== value.zip返回HTML中的城市和州,我可以实现该部分,但在jQuery部分我不知道如何获取索引。 I tried using .eq and .get and it won't work. 我尝试使用.eq和.get,但它不起作用。

Thanks! 谢谢!

Please see my Plunk I am pretty sure this is what you were after. 请看我的Plunk我很确定这就是你所追求的。

Your jQuery each is fine. 你的jQuery每个都很好。 You just need to check the value of the inputted zip against the Array using jQuery $.inArray function to get the index: 您只需要使用jQuery $ .inArray函数检查输入的zip对Array的值,以获取索引:

$.inArray(value, myZips.zipcodes);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM