标签:
(function($){
$.fn.AjaxSelect = function(options) {
var s = { url : "" // ajax查询的网址
, change : function(obj) {} // 改变选项的回调,参数为当前的jq对象
, val : "id"
, text : "title",
data : ‘‘,
};
// var s = $.extend(defaultVal, options);
var s = typeof (options) == "string" ? $.extend(s, { url : options }) : $.extend(s, options);
var nthis = $(this);
nthis.each(function() {
var $this = $(this);
var addChange = function(jqObj) {
jqObj.change(function() {
var selects = $this.find("select");
var sthis = $(this);
selects.eq(selects.index(this)).nextAll().remove();
var sval = sthis.val();
if (sval == ‘‘)
return;
// 读数据
$.getJSON(s.url + sval, function(data) {
if (data[0]) {
// 对0号对象进行复制形式
var tpl = selects.eq(0).clone();
tpl.removeAttr(‘id‘).children().slice(1).remove();
tpl.attr(‘id‘, selects.eq(0).attr(‘id‘)+‘_‘+(selects.length+1));
$.each(data, function(i, item) {
tpl.append(‘<option value="‘ + item[s.val] + ‘">‘ + item[s.text] + ‘</option>‘);
});
$this.append(tpl);
addChange(tpl);
}
s.change(sthis);
});
});
}
addChange($this.find("select"));
});
}
})(jQuery);调用方法如下:
// AjaxSelect by: qqq
$(".ajax-select").each(function(i, e){
var $this = $(e);
var url = $this.attr(‘url‘);
var data = $this.attr(‘data‘);
var arr = data.split(‘,‘);
$this.AjaxSelect({url: url, text: ‘name‘, val: ‘id‘, data: data, change: function(obj){
var ind = obj.index();
if( obj.val() == arr[ind] ){
obj.next().val( arr[ind+1] ).change();
}
} });
$this.find("select").eq(0).val(arr[0]).change();
});HTML
<dd class="ajax-select" url="index.php?pid=" data="1,2,3"> <select id="aaa" name="aaa"> <option value="">请选择</option> <option value="1">111</option> </select> </dd>
标签:
原文地址:http://my.oschina.net/skq/blog/510326