Jquery实现省市级联效果一

来源:互联网 发布:dnf数据修改器 编辑:程序博客网 时间:2024/05/14 23:57
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  <script src="jquery-1[1].2.6.js" type="text/javascript"></script>  <script src="jquery.provincesCity.js" type="text/javascript"></script> <script>/********** 省级数据 **********/var GP =['北京','广东','海外'];/********** 市级数据 **********/var GT = [['北京1','北京2'],['广东1','广东2','广东3'],['阿根廷1','埃及1']];/********** 市二级数据 **********/var GC =[[['北京11','北京12','北京13'],['北京21','北京22']],[['广东11','广东12','广东13'],['广东21','广东22'],['广东31']],[['阿根廷1'],['埃及1']]];//调用插件$(function(){$("#test").ProvinceCity();}); </script> <style>#test select{width:100px;margin-left:20px;} </style></head><body><div id="test"></div></body></html>
/** * jQuery :  城市联动插件 * @author   XiaoDong <cssrain@gmail.com> * http://www.cssrain.cn * @example  $("#test").ProvinceCity(); * @params   暂无 */$.fn.ProvinceCity = function(){var _self = this;//定义3个默认值_self.data("province",["请选择", "请选择"]);_self.data("city1",["请选择", "请选择"]);_self.data("city2",["请选择", "请选择"]);//插入3个空的下拉框_self.append("<select></select>");_self.append("<select></select>");_self.append("<select></select>");//分别获取3个下拉框var $sel1 = _self.find("select").eq(0);var $sel2 = _self.find("select").eq(1);var $sel3 = _self.find("select").eq(2);//默认省级下拉if(_self.data("province")){$sel1.append("<option value='"+_self.data("province")[1]+"'>"+_self.data("province")[0]+"</option>");}$.each( GP , function(index,data){$sel1.append("<option value='"+data+"'>"+data+"</option>");});//默认的1级城市下拉if(_self.data("city1")){$sel2.append("<option value='"+_self.data("city1")[1]+"'>"+_self.data("city1")[0]+"</option>");}//默认的2级城市下拉if(_self.data("city2")){$sel3.append("<option value='"+_self.data("city2")[1]+"'>"+_self.data("city2")[0]+"</option>");}//省级联动 控制var index1 = "" ;$sel1.change(function(){//清空其它2个下拉框$sel2[0].options.length=0;$sel3[0].options.length=0;index1 = this.selectedIndex;if(index1==0){//当选择的为 “请选择” 时if(_self.data("city1")){$sel2.append("<option value='"+_self.data("city1")[1]+"'>"+_self.data("city1")[0]+"</option>");}if(_self.data("city2")){$sel3.append("<option value='"+_self.data("city2")[1]+"'>"+_self.data("city2")[0]+"</option>");}}else{$.each( GT[index1-1] , function(index,data){$sel2.append("<option value='"+data+"'>"+data+"</option>");});$.each( GC[index1-1][0] , function(index,data){$sel3.append("<option value='"+data+"'>"+data+"</option>");})}}).change();//1级城市联动 控制var index2 = "" ;$sel2.change(function(){$sel3[0].options.length=0;index2 = this.selectedIndex;$.each( GC[index1-1][index2] , function(index,data){$sel3.append("<option value='"+data+"'>"+data+"</option>");})});return _self;};