jquery select操作和联动操作
1 (function(){ 2 //select操作 3 $.fn.loadSelect = function(opt){ 4 opt = $.extend({}, { 5 required:false,//为真则添加<option value="" selected="selected">required值</option> 6 nodata:null,//子级无数据时 select 的状态。可设置为:"none"(display隐藏) | "hidden"(visibility隐藏) | 无 7 data:[], 8 loadCall:function(){} 9 }, opt); 10 var d = {}, callback = function(data, s){ 11 var html = ''; 12 $.each(data||[], function(i,n){ 13 d = n.id ? n : { 14 id:i, 15 text:n 16 }; 17 html += '<option value="'+d.id+'"'+((opt.def != undefined && (opt.def == d.id || opt.def == d.text)) ? ' selected="selected"' : '')+'>'+d.text+'</option>'; 18 }); 19 s.html(r+html); 20 (r || html) && s.trigger('change'); 21 switch(opt.nodata){ 22 case 'none': 23 html === '' ? s.hide() : s.show(); 24 break; 25 case 'hidden': 26 s.css('visibility', html === '' ? 'hidden' : 'visible'); 27 break; 28 } 29 $.isFunction(opt.loadCall) && opt.loadCall.call(s); 30 }, r = opt.required ? '<option value="">'+($.type(opt.required) == 'string' ? opt.required : '-请选择-')+'</option>' : ''; 31 return this.each(function(){ 32 var s = $(this); 33 if(s.is('select')){ 34 if(typeof(opt.data) === 'string'){ 35 s.empty(); 36 $.getJSON(opt.data, function(json){ 37 callback(json, s); 38 }); 39 }else{ 40 callback(opt.data, s); 41 } 42 } 43 }); 44 }, 45 //select联动 46 $.fn.linkage = function(opt){ 47 opt = $.extend({}, { 48 build:true,//自动创建不存在的? 49 selects:['#city', '#area'],//子集select,按顺序,jquery选择器(.#) 50 seldef:[],//默认值,1以后和上项对应,可是id或者text 51 required:true, 52 nodata:'', 53 url:'/company/getCity.html?id={$id}',//子数据,string,{$id} or {$text}页码信息 54 data:[],//父级的数据 55 def:0//父级默认值 56 }, opt); 57 var mkSelect = function(i){ 58 var n = child[i], nN = $(n); 59 if( i && n && opt.build && nN.length === 0 ){ 60 var sn = n.substr(1), ci = n.substr(0, 1) == '#' ? 'id="'+sn+'"' : 'class="'+sn+'"'; 61 nN = $(child[i-1]).after('<select name="'+sn+'" '+ci+'></select>').next(); 62 } 63 64 !nN.data('linkage') && nN.change(function(){ 65 mkSelect(i+1).loadSelect({ 66 data: this.value ? opt.url.sprintf({ 67 id: this.value, 68 text: this.selectedIndex >= 0 ? this.options[this.selectedIndex].text : '' 69 }) : [], 70 nodata:opt.nodata, 71 required:opt.required, 72 def:opt.seldef[i]||'' 73 }); 74 }).data('linkage', true); 75 76 return nN; 77 }, child = opt.selects||[]; 78 child.unshift(this); 79 var s = mkSelect(0); 80 opt.data.length && s.loadSelect({ 81 data:opt.data, 82 def:opt.def 83 }); 84 return this; 85 }, 86 //jquery.printf 87 String.prototype.sprintf = function(data, def) { 88 return this.replace(/(?:\{\$)([\w\d\-\_]+)(?:\})/g, function() { 89 return data[arguments[1]]||def||''; 90 }); 91 } 92 });
示例:
1 <div class="jumbotron"> 2 <h1>联动测试</h1> 3 <select name="" id="addr_prv"></select> 4 </div> 5 <script type="text/javascript"> 6 In.ready(function(){ 7 $('#addr_prv').linkage({data:'/company/getCity.html',seldef:[37,567]}); 8 }); 9 </script>