我编辑了你的代码,现在它可以工作了(通过在小提琴中选择第一个“IT”然后选择“程序员”来检查它)。当然,如果没有“服务”,则第三个选择中不会显示任何内容。
您应该向其添加一些逻辑,以便仅当存在与您的主题相关的服务时才显示第三个选择
(function($) {
var data = [
{
"department": "IT",
"subject": [
{
"title": "Programmer",
"services": [
{
"name": "example1"},
{
"name": "example2"}
]
},
{
"title": "Solutions Architect"},
{
"title": "Database Developer"}
]},
{
"department": "Accounting",
"subject": [
{
"title": "Accountant"},
{
"title": "Payroll Officer"},
{
"title": "Accounts Clerk"},
{
"title": "Analyst"},
{
"title": "Financial Controller"}
]},
{
"department": "HR",
"subject": [
{
"title": "Recruitment Consultant"},
{
"title": "Change Management"},
{
"title": "Industrial Relations"}
]},
{
"department": "Marketing",
"subject": [
{
"title": "Market Researcher"},
{
"title": "Marketing Manager"},
{
"title": "Marketing Co-ordinator"}
]}
]
var selectedDepartment, selectedSubject;
$.fn.changeType = function() {
var options_departments = '<option>Select<\/option>';
$.each(data, function(i, d) {
options_departments += '<option value="' + d.department + '">' + d.department + '<\/option>';
});
$("select#departments", this).html(options_departments);
$("select#departments").change(function() {
var index = $(this).get(0).selectedIndex;
var d = data[index - 1]; // -1 because index 0 is for empty 'Select' option
selectedDepartment = d;
var options = '';
if (index > 0) {
options += '<option>Select<\/option>';
$.each(d.subject, function(i, j) {
options += '<option value="' + j.title + '">' + j.title + '<\/option>';
});
} else {
options += '<option>Select<\/option>';
}
$("select#subject").html(options);
})
};
$("select#subject").change(function() {
var index = $(this).get(0).selectedIndex;
selectedSubject = selectedDepartment.subject[index -1];
var options = '';
if (index > 0) {
$.each(selectedSubject.services, function(i, b) {
options += '<option value="' + b.name + '">' + b.name + '<\/option>';
});
} else {
options += '<option>Select<\/option>';
}
$("select#services").html(options);
})
})(jQuery);
$(document).ready(function() {
$("form#search").changeType();
});
在这里小提琴:
http://jsfiddle.net/fF38L/ http://jsfiddle.net/fF38L/
编辑 - 要使其在 IE8 上工作,请取消 console.log()
http://jsfiddle.net/fF38L/1/ http://jsfiddle.net/fF38L/1/