javascript实现省市区三级联动选择的代码(数据为模拟json数据)
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="js/jquery-1.11.1.min.js"></script> <style> select{ width:100px; } </style> </head> <body> 省: <select name="" id="sheng"> <option value="">请选择</option> </select> 市: <select name="" id="shi" disabled="disabled"> <option value="">请选择</option> </select> 区: <select name="" id="qu" disabled="disabled"> <option value="">请选择</option> </select> <script type="text/javascript"> //省 $.getJSON("data/local_P.json",function(date){ date.forEach(function(item){ var pOption = "<option value='"+item.id+"'>"+item.nameP+"</option>"; $("#sheng").append(pOption); }); }); //市 $("#sheng").change(function(){ $("#shi").attr("disabled",false); $("#shi").children(":not(:first)").remove(); $("#qu").children(":not(:first)").remove(); $.getJSON("data/local_S.json",function(date){ var pId = $("#sheng").val(); date.forEach(function(item){ if(item.p_id == pId){ var sOption = "<option value='"+item.s_id+"'>"+item.nameS+"</option>"; $("#shi").append(sOption); } }); }); }); //区 $("#shi").change(function(){ $("#qu").attr("disabled",false); $("#qu").children(":not(:first)").remove(); $.getJSON("data/local_q.json",function(date){ console.log(date); var sId = $("#shi").val(); date.forEach(function(item){ if(item.s_id == sId){ var qOption = "<option value='"+item.id_q+"'>"+item.nameq+"</option>"; $("#qu").append(qOption); } }); }); }); </script> </body> </html>
数据为模拟数据,注意模拟的json数据每一项都要加双引号,否则 $.getJson()获取不到数据,json数据如下;
local_P.json:
[{ "id":"1001", "nameP":"江苏" },{ "id":"1002", "nameP":"浙江" }]
local_S.json:
[{ "p_id":"1001", "s_id":"101", "nameS":"苏州" },{ "p_id":"1001", "s_id":"102", "nameS":"南通" },{ "p_id":"1002", "s_id":"201", "nameS":"金华" },{ "p_id":"1002", "s_id":"202", "nameS":"杭州" }]
local_q.json:
[{ "s_id":"102", "id_q":"10201", "nameq":"如皋" },{ "s_id":"102", "id_q":"10202", "nameq":"海门" },{ "s_id":"101", "id_q":"10203", "nameq":"吴中" },{ "s_id":"101", "id_q":"10204", "nameq":"高新区" },{ "s_id":"201", "id_q":"20203", "nameq":"金东" },{ "s_id":"201", "id_q":"20204", "nameq":"义乌" },{ "s_id":"202", "id_q":"20201", "nameq":"杭州下属市1" },{ "s_id":"202", "id_q":"20202", "nameq":"杭州下属市2" }]
以上,是自己模拟json数据写的省市区三级联动选择的例子,注意json数据的格式问题。