动态下拉从Json文件中读取数据

时间:2017-04-10 11:16:02

标签: jquery html json

我无法正常运行此功能。 这是我的html这个简单的形式。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html class="no-js">
<head>
<meta name="" content="">
<script type="js/jquery-1.8.1.min.js"></script>
<script src="js/outils.js"></script>
<title>Insert title here</title>
</head>
<body>
 <div>
      <select id="County">
      <option value="0">Select County Please</option>
      <option value="ANTRIM">ANTRIM</option>
      <option value="ARMAGH">ARMAGH</option>
  </select>
  <select id="Town"></select>
  </div>
</body>
</html>

下面是我的jquery,它位于js文件夹中名为outils.js的文件中。

jQuery().ready(function(){
var tabCounty=[];
$.getJSON('county.json', function(data) {
    $.each(data, function(index, val) {
        tabCounty[index]=val;
    }); 
});

$('#County').change(function(event) {
    $county=$(this).val();
    $htmlOption='<option value="0">Select County Please</option>';
    if($county!=0)
    {
        $.each(tabCounty[$county], function(key, value){
             $htmlOption+='<option 
value="'+value[0]+'">'+value[1]+'</option>';
        }); 
    }
    $('#Town').html($htmlOption);
});
});

最后下面是我的json文件名county.json,它放在js文件夹中。

{
"ANTRIM":[
["1","AHOGHILL"],
["2","ALDERGROVE"],
["3","ANDERSONSTOWN"],
["4","ANTRIM"],
["5","ARDDOYNE"]
],
"ARMAGH":[
["1","AGHACOMMON"],
["2","AGHALEE"],
["3","ALLISTRAGH"],
["4","ALTNAMACKEN"],
["5","ANNAGHMORE"],
["6","ARMAGH"]
]
}

提前谢谢。

戴夫

0 个答案:

没有答案