我动态创建选项。我绑定所有值,但是当我从下拉菜单中选择值时,它不会显示在组合框中。 帮我解决这个问题。提前谢谢
HTML:
<select name= "cityNameOption" id = "cityNameOption" >
<option value="0">All</option></select>
JS:
// cityList = [{"id":3,"name":"Hospitals"},{"id":1,"name":"Hotels"},{"id":2,"name":"Shopping Mall"}];
var cityObject = jQuery.parseJSON(cityList);
var cityOptions = document.getElementById("cityNameOption");
for ( var i = 1; i <= cityObject.length; i++) {
cityOptions.options[i] = new Option(cityObject[i - 1].name, cityObject[i - 1].id);
}
答案 0 :(得分:1)
试试这个:
<select name= "cityNameOption" id = "cityNameOption" >
<option value="0">All</option>
</select>
<script type="text/javascript">
//warning 1: js-code must be after HTML
//warning 2: JSON-object must be as a string;
var cityList = '[{"id":3,"name":"Hospitals"},{"id":1,"name":"Hotels"},{"id":2,"name":"Shopping Mall"}]';
var cityObject = $.parseJSON(cityList);
for ( var i = 1; i <= cityObject.length; i++) {
$("#cityNameOption").append('<option value='+cityObject[i - 1].id+'>'+cityObject[i - 1].name+'</option>');
}
</script>