修改自
* 作者:天天无用
* http://blog.csdn.net/luq885/archive/2007/07/31/1719538.aspx
* blog: http://blog.csdn.net/luq885
* 作者:天天无用
* http://blog.csdn.net/luq885/archive/2007/07/31/1719538.aspx
* blog: http://blog.csdn.net/luq885
- var text;
- var value;
- var type;
- var selected;
- var keep;
- jQuery.fn.FillOptions = function(url,options,endfn){
- if(url.length == 0) throw "request is required";
- text = options.textfield || "text";
- value = options.valuefiled || "value";
- type = options.datatype.toLowerCase() || "json";
- if(type != "xml")type="json";
- keep = options.keepold?true:false;
- selected = options.selectedindex || 0;
- $.ajaxSetup({async:false});
- var datas;
- if(type == "xml")
- {
- $.get(url,function(xml){datas=xml;});
- }
- else
- {
- $.getJSON(url,function(json){datas=json;});
- }
- if(datas == undefined)
- {
- alert("no datas");
- return;
- }
- this.each(function(){
- if(this.tagName == "SELECT")
- {
- var select = this;
- if(!keep)$(select).html("");
- addOptions(select,datas);
- }
- });
- /*给FillOptions 也附加了 endfn 参数 */
- if(typeof endfn =="function") endfn();
- /*解决ie浏览器的刷新 selected的不起作用 http://support.microsoft.com/kb/185123/zh-cn */
- if($.browser.msie && selected) {
- $('option[value='+selected+']',this).attr('selected',true);
- }
- }
- function addOptions(select,datas)
- {
- var options;
- var datas;
- if(type == "xml")
- {
- $(text,datas).each(function(i){
- option = new Option($(this).text(),$($(value,datas)[i]).text());
- if($($(value,datas)[i]).text()==selected)option.selected=true;
- select.options.add(option);
- });
- }
- else
- {
- $.each(datas,function(i,n){
- option = new Option(eval("n."+text),eval("n."+value));
- if(eval("n."+value)==selected) {
- option.selected='selected';
- }
- select.options.add(option);
- });
- }
- }
- jQuery.fn.CascadingSelect = function(target,url,options,endfn){
- $.ajaxSetup({async:false});
- if(target[0].tagName != "SELECT") throw "target must be SELECT";
- if(url.length == 0) throw "request is required";
- if(options.parameter == undefined) throw "parameter is required";
- this.change(function(){
- var newurl = "";
- urlstr = url.split("?");
- newurl = urlstr[0] + "?" + options.parameter + "=" + $(this).val() + "&" +urlstr[1];
- target.FillOptions(newurl,options,endfn);
- });
- /*可以联动二级三级的select*/
- if(options.selectedindex) {
- $(this).trigger('change');
- }
- }
- jQuery.fn.AddOption = function(text,value,selected,index){
- option = new Option(text,value);
- this[0].options.add(option,index);
- this[0].options[index].selected = selected;
- }