将JSON条目映射到选择选项

时间:2017-02-26 19:10:18

标签: javascript jquery json

我有一个简单的课程Pet

public class Pet{
   private name;
   private age;
}

HashMap<String,<Pet>> - String值是孩子的名字。 在html文件中,我在Json中获取此hashmap,例如:

{"Jon":[{"name":"dog","age":5},{"name":"cat","age":4},{"name":"parrot","age":3}],"Paul":[{"name":"parrot","age":3}]}

我的html中有两个select,第一个代表孩子的名字,第二个代表宠物:

       <select id="Child">
           <option value="Jon">Jon</option>
           <option value="Paul">Paul</option>
        </select>
        <select id="Pet">
        </select>

我想选择child's name,然后为此孩子输入select的第二个Pets名称。我知道加载所有数据然后使用“隐藏”和“显示”之类的东西是不可能的。那么decode我的Json对某些数组的最佳方法是什么,然后将其动态添加到清除select

@Update 我的HTML:

<html>
    <head>
    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script>
// Parse the JSON string into a proper object
        let data = JSON.parse('{"Jon":[{"name":"dog","age":5},{"name":"cat","age":4},{"name":"parrot","age":3}],"Paul":[{"name":"parrot","age":3}]}');

        // References to both SELECT elements
        let child = document.getElementById('Child');
        let pet = document.getElementById('Pet');

        // An event listener to handle changes to the child-select
        child.addEventListener('change', function () {
            // Attempt to look-up the selected value in our JSON
            let option = data[this.value];

            // Proceed only if a match (with depth) is found
            if (option && option.length) {
                // Create a fragment, and add option elements
                let fragment = document.createDocumentFragment();

                option.forEach(function (item) {
                    let entry = document.createElement("option");
                    entry.value = item.name;
                    entry.textContent = item.name;
                    fragment.appendChild(entry);
                });

                // Clear the pet-select of any values, re-populate
                pet.innerHTML = '';
                pet.appendChild(fragment);
            }
        });
    </script>
    </head>

    <body>
        <select id="Child">
          <option value="Jon">Jon</option>
          <option value="Paul">Paul</option>
        </select id="Pet">
        <select id="Pet">
        </select>       
    </body>
</html>

2 个答案:

答案 0 :(得分:1)

我没有测试过以下内容,但它可能会以编写。有关进一步说明,请参阅内联注释:

// Only proceed once the DOM has been constructed
document.addEventListener('DOMContentLoaded', function () {

    // Parse the JSON string into a proper object
    let data = JSON.parse('{"Jon":[...],"Paul":[...]}');

    // References to both SELECT elements
    let child = document.getElementById('Child');
    let pet = document.getElementById('Pet');

    // An event listener to handle changes to the child-select
    if (child && pet) {
        child.addEventListener('change', function () {
            // Attempt to look-up the selected value in our JSON
            let option = data[this.value];

            // Proceed only if a match (with depth) is found
            if (option && option.length) {
                // Create a fragment, and add option elements
                let fragment = document.createDocumentFragment();

                option.forEach(function (item) {
                    let entry = document.createElement("option");
                    entry.value = item.name;
                    entry.textContent = item.name;
                    fragment.appendChild(entry);
                });

                // Clear the pet-select of any values, re-populate
                pet.innerHTML = '';
                pet.appendChild(fragment);
            }
        });
    }

});

答案 1 :(得分:0)

如果您尝试将Pets select链接到其所有者,则可以使用JQuery Chained插件

    var values = {
        "Jon": [{"name": "dog", "age": 5}, {"name": "cat", "age": 4}, {"name": "parrot", "age": 3}],
        "Paul": [{"name": "parrot", "age": 3}]
    }
    $(function () {
        for (var key in values) {
            for (var i = 0; i < values[key].length; i++) {
                $('#Pet').append($('<option>',
                    {
                        value: values[key][i].name,
                        text: values[key][i].name,
                        class: key
                    }));
            }
        }
        $("#Pet").chained("#Child");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-chained/1.0.0/jquery.chained.js"></script>
    <select id="Child">
    <option value="Jon">Jon</option>
    <option value="Paul">Paul</option>
    </select>
    <select id="Pet">
    </select>