我想动态创建选择选项。我有两个数组“年”和“月”。当用户选择2011时,其下一个下拉列表中应显示其各自的月份。例如
如果我们选择2009,则下一个下拉选项应为“dec”,“oct”,“feb”
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function (){
$('#first').change(function(){
var year= new Array('2011','2010','2009');
var month= new Array('jan_feb_march','jan_march_april','dec_oct_feb');
var yearVal= $('#first option:selected').text();
for(i=0; i<year.length;i++){
if(year[i]==yearVal){
var months=month[i]
}
}
var y= months.split('_');
for (z=0;z<y.length;z++){
$('#second').append("<option>'"+y[z]+"'</option>")
}
})
})
</script>
</head>
<body>
<div class="menu">
<select id="first">
<option>select</option>
<option>2011</option>
<option>2010</option>
<option>2009</option>
</select>
<select id="second"></select>
</div>
</body>
答案 0 :(得分:3)
见这个DEMO:
http://jsfiddle.net/rathoreahsan/vMuev/
<强> JQUERY:强>
var categories = {
"None":[{value:'3', text:'No cataegory selected'}],
"2011":[{value:'1', text:'jan_feb_march'}],
"2010":[{value:'2', text:'jan_march_april'}],
"2009":[{value:'3', text:'dec_oct_feb'}]
};
function selectchange(){
var select = $('[name=items]');
select.empty();
$.each(categories[$(':selected', this).text()], function(){
select.append('<option value="'+this.value+'">'+this.text+'</option>');
});
}
$(function(){
$('[name=category]').on('change', selectchange);
});
希望这会有用: - )
答案 1 :(得分:2)
试试这个:
$("<option> some value </option>").appendTo($("#second"));