我创建了两个使用jquery动态填充的选择菜单:
#container {
width: 100%;
display: table;
}
.row {
display: table-row;
}
.item {
background: #c4c4c4;
width: 49%;
box-sizing: border-box;
border: 1px solid black;
display: table-cell;
}

jQuery(function($) {
CateTypes();
function CateTypes() {
var cateAndTypes = {
'Select': ['Select a Category first...'],
'Colors': ['Red', 'Blue', 'Green', 'Orange', 'Purple', 'Yellow'],
'Shapes': ['Circle', 'Square', 'Triangle', 'Rectangle', 'Octagon'],
'Sizes': ['Huge', 'Big', 'Small', 'Tiny'],
};
//populate Category
$.each(cateAndTypes, function(c, t) {
$('#category').append('<option value=' + c + '>' + c + '</option>');
});
//populate Type
$('#category').on("change", function() {
var $Types = $('#type');
$Types.html("");
var Types = cateAndTypes[$(this).val()];
$.each(Types, function(c, t) {
$Types.append('<option>' + t + '</option>');
});
});
}
});
&#13;
我的问题是如何在加载时使用#Category菜单中最初选择的选项填充#Type菜单。
答案 0 :(得分:1)
使用trigger('change')
创建#category选项后触发更改事件。
jQuery(function($) {
CateTypes();
function CateTypes() {
var cateAndTypes = {
'Select': ['Select a Category first...'],
'Colors': ['Red', 'Blue', 'Green', 'Orange', 'Purple', 'Yellow'],
'Shapes': ['Circle', 'Square', 'Triangle', 'Rectangle', 'Octagon'],
'Sizes': ['Huge', 'Big', 'Small', 'Tiny'],
};
//populate Category
$.each(cateAndTypes, function(c, t) {
$('#category').append('<option value=' + c + '>' + c + '</option>');
});
$('#category').prop('selectedIndex', 2);
//populate Type
$('#category').on("change", function() {
var $Types = $('#type');
$Types.html("");
var Types = cateAndTypes[$(this).val()];
$.each(Types, function(c, t) {
$Types.append('<option>' + t + '</option>');
});
}).trigger('change');
//-----^^^^^^^^^^^^^^^^^^----------
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<label>First, select a Category:</label>
<br>
<select id="category"></select>
</p>
<p>
<label>Then, select a Type:</label>
<br>
<select id="type"></select>
</p>