Jquery 对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2007932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:34:03  来源:igfitidea点击:

Jquery array of objects

jquery

提问by Aanu

I have an array of objects in session. This has been populated in select list. based on the selected item from the list, I would have to pre-populate the form with the attributes of the object selected.

我在会话中有一组对象。这已填充在选择列表中。基于从列表中选择的项目,我必须用所选对象的属性预先填充表单。

Please help.

请帮忙。

  • Aanu
  • 阿努

回答by Darin Dimitrov

You could store employee information into a javascript object:

您可以将员工信息存储到 javascript 对象中:

var employees = [
    { id: '1', sex: 'm', city: 'Paris' }, 
    { id: '2', sex: 'f', city: 'London' },
    ... etc fill this in a foreach loop
];

Next you bind to the change event of the select box:

接下来绑定到选择框的更改事件:

$(function()
{
    $('select#id_of_the_employees_select').change(function(e) {
        // Get the current selected employee id
        var selectedEmployeeId = $(this).val();
        // find the corresponding employee in the list
        var emps = $.grep(employees, function(n, i) {
            return n.id == selectedEmployeeId;
        });
        if (emps.length > 0) {
            var employee = emps[0];
            // fill the form elements with employee data:
            $('#employee_sex').val(employee.sex);
            $('#employee_city').val(employee.city);
        }
    });
});