我有这段代码,我正在使用它根据第一个下拉列表过滤第二个下拉列表。它与onChange方法一起工作,它的作用是,它从选择的第一个下拉选项中获取值,然后在第二个下拉列表中查找并匹配选项"data-value"进行过滤。
$(document).ready(function() {
// get first dropdown and bind change event handler
$('#p-city').change(function() {
// get optios of second dropdown and cache it
var $options = $('#p-nhb')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
});
});
我在表单上使用它,选项将被保存,那么如果已经选择了某些内容,我如何在页面加载时运行过滤器?
在$('#p-city').change(function()
后添加$('#p-city').trigger('change');
,如下面的代码所示。这应该肯定有效,希望它确实如此.我已经尝试了相同的方法 http://jsfiddle.net/heera/Gyaue/jsfiddle,默认情况下只需选择第一个选项并在结束时触发更改事件即可工作
$(document).ready(function() {
// get first dropdown and bind change event handler
$('#p-city').change(function() {
// get optios of second dropdown and cache it
var $options = $('#p-nhb')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
})
$('#p-city').trigger('change');
});