0

我想动态创建选择选项。我有两个数组“年”和“月”。当用户选择 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>
4

2 回答 2

3

看这个演示:

http://jsfiddle.net/rathoreahsan/vMuev/

查询:

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);
});

希望这会有用:-)

于 2012-07-09T05:26:57.227 回答
2

试试这个:

$("<option> some value </option>").appendTo($("#second"));
于 2012-07-09T05:17:27.700 回答