AI智能
改变未来

利用JQuery实现省市县三级联动

<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>Insert title here</title><script src=\"../js/jquery-1.11.3.min.js\"></script><script src=\"../js/data.js\"></script><script type=\"text/javascript\">$(function() {//遍历省份$(provinces).each(function(i, o) {var str = \"<option value=\\\"\"+i+\"\\\">\" + o + \"</option>\";$(\'#province\').append(str);//alert(str);});//省份改变$(\'#province\').on(\'change\', function() {//获取省份的下标值pIndex = $(\'#province\').find(\':selected\').attr(\'value\')//alert(pIndex);//市和县重置,显示请选择$(\'#city\').empty().append(\"<option value=\\\"\\\">请选择</option>\");$(\'#area\').empty().append(\"<option value=\\\"\\\">请选择</option>\");//遍历市$(cities[pIndex]).each(function(i, o) {//alert($(cities[pIndex]));var str = \"<option value=\\\"\"+i+\"\\\">\" + o + \"</option>\";//alert(o);//把市的值加入进去$(\'#city\').append(str);});})//市改变$(\'#city\').on(\'change\', function() {cIndex = $(\'#city\').find(\':selected\').attr(\'value\');//县重置,显示请选择$(\'#area\').empty().append(\"<option value=\\\"\\\">请选择</option>\");//遍历县$(areas[pIndex][cIndex]).each(function(i, o) {var str = \"<option value=\\\"\"+i+\"\\\">\" + o + \"</option>\";$(\'#area\').append(str);});});});</script></head><body><select name=\"\" id=\"province\"><option value=\"\">请选择</option></select>省<select name=\"\" id=\"city\"><option value=\"\">请选择</option></select>市<select name=\"\" id=\"area\"><option value=\"\">请选择</option></select>县</body></html>

data.js代码:

var provinces =[\'山西\',\'山东\',\'河南\',\'河北\'];var cities = [[\'太原\',\'晋中\',\'大同\',\'阳泉\'],[\'济南\',\'青岛\',\'威海\'],[\'郑州\',\'洛阳\'],[\'石家庄\',\'保定\']];var areas = [[[\'小店\',\'迎泽\',\'杏花岭\',\'尖草坪\'],[\'榆次\',\'左权\',\'寿阳\'],[\'左云\'],[\'平定\',\'盂县\']],[[\'济南地区1\',\'济南地区2\'],[\'青岛地区1\',\'青岛地区2\'],[\'威海地区1\',\'威海地区2\'],],[[\'郑州地区1\',\'郑州地区2\'],[\'洛阳地区1\',\'洛阳地区2\'],],[[\'石家庄地区1\',\'石家庄地区2\'],[\'保定地区1\',\'保定地区2\'],],]

效果如下:

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 利用JQuery实现省市县三级联动