【问题标题】:Get JSON into select box and display an answer with Jquery将 JSON 放入选择框并使用 Jquery 显示答案
【发布时间】:2014-03-04 05:02:33
【问题描述】:

我有一个巨大的 JSON 文件,每个对象都有三个属性:

[
    {
        "Product": "Hurtta Frost Jacket",
        "Dog Type": "Affenpinscher",
        "Size for the dog": "25, 30"
    },
    {
        "Product": "Hurtta Frost Jacket",
        "Dog Type": "Afghan Hound",
        "Size for the dog": "60, 65"
    }
]

狗的类型和尺寸。

What I need is to make to select boxes one for the Product and one for the Dog Type, and when these two options are selected the size for the dog for that object will display in a div anywhere.实现这一目标的正确方法是什么?

【问题讨论】:

  • 对不起,但我不明白为什么有 2 个“选择框”:在您的示例中,每个产品都有一个对应的狗类型。而昏迷的尺寸,是不是意味着它是两种不同的尺寸?

标签: jquery arrays json option


【解决方案1】:
<select id="product"><option value="">Select Product</option></select>
<select id="type"><option value="">Select Dog Type</select></select>
<br>Size:
<div id="size"></div>

$(function () {
    json_obj = [{
        "Product": "Hurtta Frost Jacket",
            "Dog Type": "Affenpinscher",
            "Size for the dog": "25, 30"
    }, {
        "Product": "Hurtta Frost Jacket",
            "Dog Type": "Afghan Hound",
            "Size for the dog": "60, 65"
    }];
    var products_added = {};
    var types_added = {};
    $.each(json_obj, function () {
        if (!products_added[this.Product]) {
            $("#product").append($("<option/>", {
                value: this.Product,
                text: this.Product
            }));
            products_added[this.Product] = true;
        }
        if (!types_added[this["Dog Type"]]) {
            $("#type").append($("<option/>", {
                value: this["Dog Type"],
                text: this["Dog Type"]
            }));
            types_added[this["Dog Type"]] = true;
        }
    });

    $("#product, #type").change(function () {
        $("#size").empty();
        var product = $("#product").val();
        var type = $("#type").val();
        if (product && type) {
            $.each(json_obj, function () {
                if (product == this.Product && type == this["Dog Type"]) {
                    $("#size").text(this["Size for the dog"]);
                    return false; // terminate the loop
                }
            });
        }
    });
});

DEMO

【讨论】:

  • 感谢您的快速回复。我在 $("#product, #type").change(){ 开头的行上出现语法错误
  • 已修复,我在上一行缺少一个右括号
  • 跟.change()有关系{}
  • 我添加了 .change(function(){})
  • 所以,我修复了语法错误,选项框显示良好,但 #size 潜水文本没有改变
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 2011-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多