Jquery对象数组

时间:2010-01-05 17:41:05

标签: jquery

我在会话中有一组对象。这已在选择列表中填充。根据列表中的选定项目,我必须使用所选对象的属性预填充表单。

请帮忙。

  • Aanu

1 个答案:

答案 0 :(得分:13)

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

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

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

$(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);
        }
    });
});
相关问题